so I wanted to do implement a sort of thing where I can put custom attributes in HTML elements which will be taken as props by a react component. Something like:
function someFunction(props) {
return <h1>props.something</h1>
}
HTML:
<div id="someElement" data-something="some text"></div>
renders:
<h1>some text</h1>
I THINK something like this could work, but I don't think its the best approach
let render_div = document.getElementById("someElement")
render(<someElement something={render_div.getAttribute("data-something")}/>, render_div)
I'm new to react so please help me :)
PS: I'm using typescript
Every data- attribute you set on an HTML element is available inside the element.dataset property. Keep in mind though that there's a naming conversion from dash-style to camelcase (see MDN).
What you should be able to do is something like the following:
<div id="root" data-title="title" data-my-text="my-injected-text" />
import ReactDOM from 'react-dom';
import App from './App';
const rootNode = document.getElementById('root');
const props = element.dataset; // { title: 'title', myText: 'my-injected-text' }
ReactDOM.render(App, props, rootNode);