0

I'm trying to display an element from my items array. I can log the element to the console... but can't get it render. In my setState, I made itemDetail that takes the first element from the items array: (perhaps there's a better way to do that?)

this.setState({ items: items, itemDetail: items[0], value: this.state.value })

When I try to call {itemDetail} it is giving me the error:

"Objects are not valid as a React child (found: object with keys {id, name})...."

Full Code below. How can I render the first element from my array in React? Or better yet, display an element by Id. Thanks.

constructor(props){
    super(props);
    this.state = {
      items: []
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  componentDidMount(){
    const items = [
      {
        'id': 0,
        'name': 'firstName'
      },
      {
        'id': 1,
        'name': 'secondName'
      }
    ];

    this.setState({ items: items, itemDetail: items[0] });
  }


  render(){

    const { items, itemDetail } = this.state;

    console.log(itemDetail);

    return(
      <div className="container">
        {itemDetail}
      </div>
    );
  }

3 Answers 3

1

React doesn't know how to render object itemDetail. Let's help him:

render(){

    const { items, itemDetail } = this.state;

    console.log(itemDetail);

    return(
        <div className="container">
            <div className="item-id">{itemDetail.id}</div>
            <div className="item-name">{itemDetail.name}</div>
        </div>
    );
}

Hope this will be useful.

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

1 Comment

This was useful. Thank you for the answer!
1

Your state has to be like following since you are accessing itemDetails in render()

this.state = {
    items: [],
    itemDetail: {} 
}

1 Comment

ahh, I missed this. Thank you!
0
const itemsArray = this.state.items
return(
      <div className="container">
        {itemsArray && itemsArray[0]}
      </div>

if you are deciding based on some props or state value, you can do something like

const itemsArray = this.state.items
const slectedIndex = this.state.selectedIndex or this.props.selectedIndex//depends how you are getting selectedindex logic
return(
      <div className="container">
        {itemsArray && itemsArray[slectedIndex]}
      </div>

1 Comment

Thank you for the answer! I was able to apply similar logic to solve my problem.

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.