Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
Schroedinger Avatar asked Mar 12 '18 02:03

Schroedinger


1 Answers

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>
like image 145
Kevin Qian Avatar answered Sep 19 '22 06:09

Kevin Qian