skip to Main Content

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?

2

Answers


  1. 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>
       )
    
    }
    
    Login or Signup to reply.
  2. const generateAndInjectMarkup = () => {
      return <p> Hello </p>;
    };
    
    const MainComponent = () => {
      const [showMarkup, setShowMarkup] = useState(false);
      return (
        <div>
          <button onClick={() => setShowMarkup(true)}> generate </button>
          <div ref={container} id="target">
            {showMarkup ? generateAndInjectMarkup() : null}
          </div>
        </div>
      );
    };
    

    This should do the work!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search