Reputation: 6013
I need to do some updates to a very old school website. Currently the layout is table based and hand-coded. My thought was to use React do do away with some of the repetitive coding, specifically loop through an array of data and construct the table rows with JSX. I see that it's possible to embed React components in HTML here -- https://reactjs.org/docs/add-react-to-a-website.html -- but I'm not sure how to make those components reusable, that is, I'm not sure how to pass props to them from the HTML file.
My plan is to read data arrays from a file specific to each html page
<script type="text/javascript" src="data_page_x.js"></script>
and then pass it to the component, which would read it as a prop, then spit out the table rows.
Is this possible? Is there a better way to do it?
Upvotes: 0
Views: 902
Reputation: 919
You can use something like:
const initialData = document.getElementById('initial-data').textContent;
ReactDOM.render(
<MyReactElement initialData={JSON.parse(initialData)} />,
document.getElementById('root')
);
Or if you are not using JSX, you can pass data to ReactElement using React.createElement
https://reactjs.org/docs/react-api.html#createelement
Passing data using React.createElement
const domContainer = document.querySelector('#like_button_container');
const e = React.createElement;
ReactDOM.render(
e(
LikeButton,
{initialData: JSON.parse(initialData)}
), domContainer);
Upvotes: 2