简体   繁体   中英

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

I have a component build in React myComponent.js

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

In my Html, I want to render it twice, the HTML is as following:

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

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

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

<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')
);

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 div s 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')
);

You could do

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

Or You could also have two div tags with different id

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

then

ReactDOM.render(
  <MyComponent />,
  document.getElementById('one')
);

ReactDOM.render(
  <MyComponent />,
  document.getElementById('two')
);

Another option is to use a class to define elements to render in:

<div id="my-id-one" class="render-here"></div>
some html
<div id="my-id-two" class="render-here"></div>

Then in js :

let elements = document.getElementsByClassName('render-here');
elements.map(element => ReactDOM.render(
  <MyComponent />,
  element
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM