简体   繁体   中英

Render multiple widget React components

I would like to render widgets in html multiple times. I have 3 div with the same id, but with different attributes, and I would like to render my react component 3 times on the page. Now I get only the first component.

Html:

<div id="myapp" att="1"></div>
<!-- Something else -->
<div id="myapp" att="2"></div>
<!-- Something else -->
<div id="myapp" att="3"></div>
<script type="text/javascript" src="index.js"></script>

index.js

const container = document.getElementById('myapp');
ReactDOM.render(
 <App
  att={container.getAttribute('att')}
 />,
 container,
);

Do you have any suggestion how can I render my component three times?

Your App component would contain the components that you would want to render.

So in App.js you would have something like this, you could pass attributes to the divs using props

const widgetOne = props => (
  <div att={props.attribute}>
    <h1>WidgetTwo</h1>
  </div>
);

const widgetTwo = props => {
  <div att={props.attribute}>
    <h1>WidgetTwo</h1>
  </div>;
};

const widgetThree = () => {
  <div>
    <h1>WidgetThree</h1>
  </div>;
};

function App() {
  return (
    <div className="App">
      <widgetOne att={1} />
      <widgetTwo att={2} />
      <widgetThree />
    </div>
  );
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

Your html would have a div that the App component would hook onto like so <div id="root"></div>

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