Skip to content

Instantly share code, notes, and snippets.

@ibqn
Forked from diegoquintanav/index.html
Created November 26, 2022 22:28
Show Gist options
  • Save ibqn/64783e91379fc86a6ef79bc005099684 to your computer and use it in GitHub Desktop.
Save ibqn/64783e91379fc86a6ef79bc005099684 to your computer and use it in GitHub Desktop.
How to pass variables from html script tags to the react.js DOM
<div id="container" data-stuff="my variable">
<!-- This element's contents will be replaced with your component. -->
</div>
<script>
window.test = "my react test";
window.dumbname = "martin"
// notice that `stuff` is not passed directly, it is passed using `data-stuff="my variable"` through `container.dataset`
</script>
class Hello extends React.Component {
render() {
return <div>Hello {this.props.somename}. This is a {this.props.test}.
One can also add variables like "{this.props.stuff}" was passed using the `data-$` class</div>;
}
}
ReactDOM.render(
<Hello {...(container.dataset)} test={test} somename={dumbname}/>, //stuff in container
document.getElementById('container')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment