Kirk Ross
Kirk Ross

Reputation: 7153

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.

Where have I gone wrong here?

import React from 'react';

var user;
$.getJSON("./json/user.json", function(json){
    user = json;
});

const User = ({ user }) => (

  <div className="user">
    <div className="avatar">
      <img src={user.avatarSrc} height="30" />
    </div>  
    <div className="user-full-name">
      {user.fullName}
    </div>
  </div>
);

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

export default User;

LINK TO A MORE DETAILED STRUCTURE OF MY APP:

React - passing JSON objects to all stateless child components

Upvotes: 1

Views: 7957

Answers (2)

keslert
keslert

Reputation: 311

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

import React from 'react';
import User from './user';

class UserContainer extends React.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} />
  }
}

export default UserContainer;

import React from 'react';

const User = ({ avatarSrc, fullName }) => (
  <div className="user">
    <div className="avatar">
      <img src={avatarSrc} height="30" />
    </div>  
    <div className="user-full-name">
      {fullName}
    </div>
  </div>
);

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

export default User;

Upvotes: 1

Aaron Beall
Aaron Beall

Reputation: 52153

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:

class User extends React.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 (
      <div className="user">
        <div className="avatar">
          { user && <img src={user.avatarSrc} height="30" /> }
        </div>  
        <div className="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.

Upvotes: 3

Related Questions