Search code examples
htmlreactjsreact-dom

How to generate react components imperatively in react?


Let's say I have a button, when I click on this button a React component should be generated and injected into the target node:

const generateAndInjectMarkup = e => {
// define my node here lets say
const nodeToInject = <p> Hello </p>

// now how do I inject and render the markup in the target node? 
} 


<div>
 <button onClick={generateAndInjectMarkup}> generate </button>
 <div ref={container} id="target"></div> {/* this is where I want to inject the jsx I want to generate */}
</div>

How do I solve this problem? I'm working on a form generator, I saw at renderToString API given by React, but I'm unsure how to inject and render the markup I have generated.

Should I use a portal or createRoot?


Solution

  • This is actually not at all different than any other declarative react problem, you might be overthinking it

    const generateStuff = () => {
       return /* some jsx */
    }
    
    
    const MyComponent = () => {
       const [generatedStuff,setGeneratedStuff] = useState(null)
    
       return (
         <div>
           <button onClick={() => setGeneratedStuff(generateStuff())}> generate </button>
           <div id="target">{generatedStuff}</div>
         </div>
       )
    
    }