Skip to content Skip to sidebar Skip to footer

React - Passing Json Object Into Const

I'm trying to get a json object into a const. I'm comfortable doing it with vars, like {this.props.user.map(function(user){... But with the stateless const, I'm not exactly sure.

Solution 1:

The way you've written this component is not stateless (the user is state), so you shouldn't be using a stateless functional component, you should be using a stateful component class:

classUserextendsReact.Component {
  static propTypes = {
    user: React.PropTypes.object
  };
  state = {};
  componentDidMount() {
    $.getJSON("./json/user.json", (json) => {
      this.setState({user: json});
    });
  }
  render() {
    let user = this.state.user;
    return (
      <divclassName="user"><divclassName="avatar">
          { user && <imgsrc={user.avatarSrc}height="30" /> }
        </div><divclassName="user-full-name">
          { user && user.fullName }
        </div></div>
    );
  }
}

Here it is working in CodePen.

Of course, you don't have to make this component stateful. You could move the state to a parent component (like a top level view) and pass the user down as props. Then you could use the stateless function component instead.

Solution 2:

You might think about doing something like this. This separates the job of fetching the data and displaying the data.

importReactfrom'react';
importUserfrom'./user';

classUserContainerextendsReact.Component {
  constructor(props) {
    super(props);
    this.state = { user: {} }
  }

  componentDidMount() {
    $.getJSON("./json/user.json", function(json) {
      this.setState({user: json})
    }
  }

  render() {
    return<User {...this.state.user} />
  }
}

exportdefaultUserContainer;

importReactfrom'react';

constUser = ({ avatarSrc, fullName }) => (
  <divclassName="user"><divclassName="avatar"><imgsrc={avatarSrc}height="30" /></div><divclassName="user-full-name">
      {fullName}
    </div></div>
);

User.PropTypes = {
  avatarSrc: React.PropTypes.string,
  fullName: React.PropTypes.string
};

exportdefaultUser;

Post a Comment for "React - Passing Json Object Into Const"