I am new to react JS. I'm using react JS in conjunction with an existing Rails app. With the help of webpacker gem i have all the dependencies available.
For some reason DOM elements are not available to react JS. In tutorials the same thing works fine. In an html.erb file i have
<div id='root' data-link='https://x.com'></div>
app/javascript/index.js file
const root = document.querySelector('#root')
ReactDOM.render(<Dashboard link={root.dataset.link} />, root)
Uncaught TypeError: Cannot read property 'dataset' of null
Also, is it possible without the use of Refs or Portals that I can have above working.
The div with id root
can't be found in the DOM because the script tag is before the div in the document. You could move the script tag after the div and it will work as expected.
<div id='root' data-link='https://x.com'></div>
<script src="/bundle.js"></script>
function Dashboard(props) { return <h1>Hello, {props.link}</h1>; } const root = document.querySelector('#root') ReactDOM.render(<Dashboard link={root.dataset.link} />, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='root' data-link='https://x.com'></div>
It's totally workable, guess you might need to put some breakpoints and check if root has been passed correctly.
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.