What is the best way to programmatically insert a new element into the DOM after it has already been rendered in Next

In my project with Next.JS 13, I am currently exploring methods to manually inject component code into an existing element in the DOM that has already been rendered. Below is the code snippet for the component:

const layouts = {
    forgotPassword: () => {
        return (
            <>
                <ManualScrollerObject className="flex v center gap2">

                <h3>
                    Forgor your password?
                </h3> 
                <Field name="Tag/Email" id="user" />
                <Field name="Password" id="pass" icon="bx bxs-lock" type="password"/>

                <div className="flex v center gap1" style={{width: '100%'}}>
                    <LoginButton>
                        Sign in
                    </LoginButton>
                    
                    <p>
                       No, no, no <a href="/signup">take me back!</a>
                    </p>
                    <p>
                        <a href="/forgot">Forgor your password?</a>
                    </p>
                </div>


                </ManualScrollerObject>
            </>
        )
    }
}

My goal is to add this specific element as a child to another element acquired through document.getElementById(), without replacing the existing children.

I have devised a separate function for this purpose, and here is my attempt:

function forgotPassword() {
    const loginScroller = document.getElementById('loginScroller');

    ReactDOM.render(
        layouts.forgotPassword(),
        loginScroller
    )    

    
}

React.render() replaces all children within the element, which is not the desired outcome. An alternative approach involves appending a separate element to the wrapper and assigning the desired element as its child. However, I find this method to be cumbersome and indirect.

Are there any efficient ways to dynamically inject the element using a function like this?

Answer №1

Utilizing states in React allows us to toggle the visibility of components. Let's take a look at an implementation:

 import { useState } from "react";

 function ToggleComponent() {
  const [showInfo, setShowInfo] = useState(false);

 return (
    <div>
      {showInfo && <InfoComponent />}
      <button onClick={() => setShowInfo(true)}>Show Info</button>
    </div>
    );
  }

This snippet of code employs a state showInfo to manage the display of InfoComponent. By clicking the button, showInfo is set to true, rendering the component on the screen.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript: set values to elements in an array

Below is the code snippet I am working with: function gotData(data){ result = data.val() const urls_kws = Object.keys(result) .filter(key => result[key].last_res > 10) var keywords = urls_kws; c ...

Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me This is the state type: export type Foo = { animals: { dogs?: Dogs[], cats?: Cats[], fishs?: Fishs[] }, animalQueue: (Dogs | Cats | Fishs)[] } Now, in a reducer I&a ...

Establish an HttpOnly cookie using JavaScript

Is it possible to convert a non-HttpOnly cookie into an HttpOnly cookie using JavaScript? ...

What is the optimal method for assigning a value to a specific key within a JavaScript JSON object?

Below is the information stored in a file called "fokontanys.json": { "vzdveg643": { "lldistrict":"Ambilobe", "id_province": 7, "id": null }, "vzvsdv5327": { "lldistrict ...

"Flashes of canvas in constant motion between animated scenes

I have a practical exercise to do for school, but I am very new to HTML/JS. The issue I am facing is that my canvas is flashing, like it erases one image and then quickly displays another. I want both images to be displayed at the same time. Here is the co ...

Tips for submitting data to the identical ejs view or partial following utilizing res.render get?

Is there a way to display data in my EJS file that is posted after the view has been rendered using res.render()? When I try to use <% date %> in my EJS file, it throws an error saying that date is not defined. This makes sense because the value is s ...

Retrieving the variable value instead of a reference using Ajax in ASP

After spending nearly two days trying to figure out this code and researching every possible solution, I still haven't been able to get it to work properly. It's likely that I'm implementing it incorrectly or missing something, so I've ...

Access the value of a variable passed from the view to the controller

Is there a way to retrieve a dynamically generated value from the view to the controller in AngularJS? <ng-option ng-repeat="w in details track by $index"> <div class="program-grid-row table-row" > <div> <a class= ...

What is the reason behind the addition of '.txt' by the Next.js `Link` Component when redirecting to `href='/'` on GitHub pages?

My website is hosted on github-pages, and I am using the Link Component from Next.js to navigate within it. However, when I click on a component with the href="/", it adds .txt to the end of the URL. My website follows the /app structure. I have ...

Error encountered while using Jquery's .each() method on a DOM element and attempting to

Trying to utilize the each() function on my DOM to dynamically retrieve a field, I encountered an issue with the following code: var new_entry = new Object(); $('div[name="declaration-line-entry"]').each(function () { new_entry.name = $(this ...

Struggling to find the element using Selenium

Hey there, I'm struggling with identifying the input id button in my HTML code while using Selenium through Java. The error message says it's unable to locate the element. Can anyone provide some guidance? I've already tried using xpath and ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Extract the JSON information to find the <highlighting> tag used to emphasize text within a specific field

{ "responseHeader": { "status": 0, "QTime": 32 }, "response": { "numFound": 21, "start": 0, "docs": [ { "description": "A unique wave design sets apart this wedding band, craft ...

What is the best way to manage communication with a database in a Node.js application?

I have a specific structure in my Express app: There is a db helper that I use to interact with my MariaDB database Here is the code snippet: var MariaSQL = require('mariasql'); var db = new MariaSQL(); var queries = { getUserByID : &a ...

mootools.floor dispose function malfunctioned

I am attempting to implement form validation with the following code: However, it does not seem to be working properly. <form name="niceform" id="third" action="" class="niceform" method="post" enctype="multipart/form-data"> <div class ...

Extracting a particular element from a sophisticated auto-complete DOM structure by drilling down into the $scope

After spending a significant amount of time trying to solve this problem, I find myself at a dead end. The simplicity of using jQuery makes me reconsider Angular, but perhaps my approach is flawed. In this scenario, the DOM structure looks like this: < ...

How can I manage file input within a Vue.js application?

After attempting to open a file input with a button, I encountered an issue. When clicking the button, the client reported: “this.$refs.image.click”. Below is my code snippet: <v-btn height="50" ...

Adjust the position if the height exceeds 100 pixels

Can someone help with this code issue? $(document).ready(function () { if ($('.pi-img').height() > 100) { $(this).css('top' , '30%'); console.log('yeah'); } }); I am encountering difficu ...

Stop the jQuery custom slide animation when there are no more items to display

I have designed a unique slider for users to view the work process https://i.sstatic.net/FLYne.png When a user clicks the button, the slider will move left or right depending on the button clicked. However, if the user clicks multiple times, the slider ma ...