13

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.

1 Answer 1

21

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>

Sign up to request clarification or add additional context in comments.

3 Comments

And bippity-boppity-boo? What does that do? How does it answer the question? Don't just blurt out code. Explain yourself ! stackoverflow.com/help/how-to-answer
@Rob I usually post code and then add comments, sorry for the confusion...
This is the way to do it, just pass a prop like you would do with any other component. To get the value of the data attribute you could also use dataset instead of getAttribute: developer.mozilla.org/en-US/docs/Learn/HTML/Howto/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.