dace
dace

Reputation: 6363

How to access JSON in a React Component?

I have a JSON object from a script tag like so:

  <script type="text/json" id="json-data">
    {'someData': 'Lorem ipsum...'}
  </script>

I would like to be able to pull this information and use it within a React component in my render method.

The issue seems to be that I need to set this to a variable within componentWillMount:

export default MyReactComponent extends Component {

  componentWillMount() {
    const test = document.getElementById('json-data').innerHTML;
  }

  render() {
    return (
      <div>
        // This is where I would like to use this data.
      </div>
    );
  }

}

Is this the best way to handle passing this data? If so, how can I access this data within the render method of my component?

Thanks!

Upvotes: 4

Views: 4250

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Store it in the component's state. The render method should only depend this.state and this.props

At the risk of oversimplifying:

  • this.props are passed from parent components
  • this.state is state that is internal to the component

Example

export default MyReactComponent extends Component {

  componentDidMount() {
    this.setState({
        test: JSON.parse(document.getElementById('json-data').innerHTML)
    });
  }

  render() {
    return <div>{this.state.test}</div>;
  },

  getInitialState: function() {
    return {test: {}}
  } 
}

Upvotes: 2

Related Questions