-1

I am new to React and also to stackoverflow,

I am trying to render this.state.searchResults as attached code

The code runs without any error, but does not render. what wrong am I doing here ?

I am exporting this component in my main js file. if I run without map method, it renders correctly.

please help

code image

 export class App extends React.Component { constructor(props) { super(props); this.state = { searchResults: [ {name: 'name1', artist: 'artist1', album: 'album1', id: 1}, {name:' name2', artist: 'artist2', album: 'album2', id: 2}, {name: 'name3', artist: 'artist3', album: 'album3', id: 3} ] } } render() { return ( <div> <h1>Ja<span class="highlight">mmm</span>ing </h1> <div className="App"> { this.state.searchResults.map( track => { return track }) } </div> </div> ); } }

4
  • 2
    Please don't post your code as an image. Instead, post it just as text. Commented Apr 15, 2022 at 15:48
  • 2
    "The code runs without any error" - I would fully expect this to produce an error. Are you sure you're checking the browser console for errors? Because an object by itself is not valid as a renderable element in React. Even if it did render, it wouldn't know how to render an object other than as something like [object Object]. Commented Apr 15, 2022 at 15:51
  • 1
    @David, you are correct. Browser console is throwing this error "Uncaught Error: Objects are not valid as a React child........." Commented Apr 15, 2022 at 16:05
  • @pAtel0158: It's because track by itself in that context is an object, and React doesn't know how you want to render it. You can render individual values from the object, or pass the object to a component which internally renders individual values from the object. But an object by itself is not renderable. Commented Apr 15, 2022 at 16:27

1 Answer 1

0

You can render object directly in JSX. Specify the object value

this.state.searchResults.map((track) => ( <p>{track.name} {track.artist} {track.album} </p> )) 
Sign up to request clarification or add additional context in comments.

2 Comments

this works, thanks Khant for replying.
@pAtel0158 You should select this answer as answered and close the question. NOT delete

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.