Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to render a component twice in an HTML page?

I have a component built using React:

myComponent.js

    ReactDOM.render(
      <MyComponent />,
      document.getElementById('my-id')
    );

In my HTML, I want to render it twice. My HTML is as following:

    <div id='my-id'></div>
    some html
    <div id='my-id'></div>

I want my React component to render twice in this page, but it only renders once for the second div. Is there anyway to render it twice?

like image 808
ewrwerwe Avatar asked Sep 01 '25 04:09

ewrwerwe


2 Answers

You can't have the same id for two or more elements in HTML. Use different ids

    <div id='my-id-one'></div>
    some html
    <div id='my-id-two'></div>

and call the ReactDOM.render separately for each id.

    ReactDOM.render(
      <MyComponent />,
      document.getElementById('my-id-one')
    );
    
    ReactDOM.render(
      <MyComponent />,
      document.getElementById('my-id-two')
    );
like image 127
Tharaka Wijebandara Avatar answered Sep 02 '25 17:09

Tharaka Wijebandara


It looks like you want to render it in 2 different places, with non-React code in between. To do that, you'll want to give your divs different IDs:

<div id='my-id></div>
some html
<div id='my-other-id></div>

Then render the component to each div:

ReactDOM.render(
    <MyComponent />,
    document.getElementById('my-id')
);

ReactDOM.render(
    <MyComponent />,
    document.getElementById('my-other-id')
);
like image 42
Mark Rabey Avatar answered Sep 02 '25 16:09

Mark Rabey