最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: How to render a component twice in an HTML page? - Stack Overflow

programmeradmin3浏览0评论

I have a ponent 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 ponent to render twice in this page, but it only renders once for the second div. Is there anyway to render it twice?

I have a ponent 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 ponent to render twice in this page, but it only renders once for the second div. Is there anyway to render it twice?

Share Improve this question edited Oct 12, 2023 at 21:26 Ed Lucas 7,3554 gold badges40 silver badges50 bronze badges asked Aug 17, 2017 at 17:14 ewrwerweewrwerwe 551 silver badge4 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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

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 ponent 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
));
发布评论

评论列表(0)

  1. 暂无评论