Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render one object from map instead all of them?

Tags:

reactjs

I have a profile object in the state of my react app, which contains an array of 6 objects.

I want to be able to render these objects separately.

      {
         this.state.profiles.map(profile => (
            <div key={profile.mainCompanyID}>
               {profile.name}
               {profile.description}
            </div>
          ))
      }

The code above will display all 6 names/descriptions. But I want the power to be able to only map through one of the objects in the array, not all of them.

Any ideas?

like image 840
BennKingy Avatar asked Jan 26 '26 03:01

BennKingy


2 Answers

filter the array before map

renderBasedOnId = id =>{
    const { profiles } = this.state
    return profiles.filter(x => x.id === id).map(item => <div>{item.name}</div>)
}

render(){
    return this.renderBasedOnId(this.state.selectedId) //just an example of usage
}
like image 136
Dupocas Avatar answered Jan 28 '26 15:01

Dupocas


You can filter out the data and then apply map.

Working Example - https://codesandbox.io/s/funny-shirley-q9s9j

Code -

function App() {
  const profileData = [
    { id: 1, name: "Tom" },
    { id: 2, name: "Dick" },
    { id: 3, name: "Harry" },
    { id: 4, name: "Nuts" }
  ];

  const selectedProfile = profileData.filter(x => x.name === "Harry");
  return (
    <div className="App">
      <h1>Test Filter and map in jsx</h1>
      {selectedProfile.map(x => (
        <li>
          {x.id} - {x.name}
        </li>
      ))}
    </div>
  );
}
like image 45
swapnesh Avatar answered Jan 28 '26 14:01

swapnesh