Search code examples
htmlreactjsreact-dom

React - Pass parameter to app with data on root element


I have a bit of an odd use case for a react app, I'd like to provide a root URL to the app based on a parameter on the element we mount the react app on.

ReactDOM.render(<MyGoodApp />, document.getElementById('root'));

Where in the HTML DOM I have

<div id="root" data-param="https://website.biz/api/"></div>

I can't find anything particularly in the documentation that covers this case. I'm constrained in deploying this app due to business constraints so need to pass the value in this way or a similar way if possible. The value will be dynamic.


Solution

  • Just do what you would normally fetch an attribute from DOM, get its attribute and send it as a prop to the React component

    class App extends React.Component {
      render() {
        return <div>{this.props.message}</div>
      }
    }
    
    const el = document.getElementById('root');
    
    ReactDOM.render(<App message={el.getAttribute('data-param')} />, el)
    <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-param="https://website.biz/api/"></div>