1

I have a list of results where each result has the following data: id, title, system, unit. This data is in the form of an object, e.g: ({id:1, title: "main engine", system: "ship", unit: "C"}).

Each result has an onclick that calls a my addFunc function that is a state. This looks like this:

class Search extends Component {
  constructor(props) {
    super(props);
    this.addFunc = this.addFunc.bind(this);
    this.state = { selectedData:[] }
  }
  addFunc(resultdata) {
    var joined = this.state.selectedData.concat(resultdata);
    this.setState({ selectedData: joined })
    console.log(joined)
  }

Currently, each object is added to my joined array when clicked, and I can see it in my console. I want to display this on the screen

3
  • Hi, Develoweb Co! Welcome to SO! Typically, in React, to display something you include it in your render() method, have you tried this? Commented Jun 19, 2020 at 17:58
  • Hi, Develoweb Co! Let me know if my answer helped any! Feedback is always welcome. Thanks! Commented Jun 19, 2020 at 18:33
  • Hi, thanks for your answer. I tried calling {this.state.selectedData} in my render() method, but this causes an error because my selectedData is an array of objects. for example, [{id:1, title: 'title'}, {id:2, title: 'hello'}]. How can I display this kind of data? Commented Jun 20, 2020 at 1:48

1 Answer 1

1

Try displaying your data by using the render() method in ReactJS.

class Search extends Component {
    // ...
    render() {
        return (
            <div>
                {this.state.selectedData}
            </div>
        );
    }
}

It seems you are storing this to the state as { selectedData: joined }, so this should work fine. Your constructor correctly initializes the state as so, this.state = { selectedData:[] }, so, hopefully this fix works right out of the box.

Find out more about render() from the ReactJS Docs: Rendering Elements.

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

2 Comments

This produces error, because my selecteddata is an array of objects, so I dont think it can just be displayed like this.
My selectedData would look something like this, for example: [{id:1, title: 'title'}, {id:2, title: 'hello'}]

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.