jagomez8
jagomez8

Reputation: 175

Rendering a single element from an array of data in React

If I was to map through an array of objects of data and only wanted to render a single element from the array based on a certain condition like below:

dataArray.map((element, i) => {
  if(i === currentElement){
    return (
        <div>{element.data}</div>
    )
  } else {
    return null;
  }
});

Would that be acceptable? this seems to return what I am after but was curious if this was the most efficient way to go about it because this still returns an array with a length of the data array with all null elements except on the desired single element.

Upvotes: 0

Views: 3365

Answers (2)

SimpleJ
SimpleJ

Reputation: 14768

You could use the find function to get the value you want to render rather than rendering a bunch of null values.

const element = dataArray.find((el, i) => i === currentElement);

if(element) {
  return (<div>{element.data}</div>);
}

Upvotes: 2

Snkendall
Snkendall

Reputation: 110

Using map on an array will return another array with your function performed on each element, so the function you are using is literally pushing the value 'null' into the return array for any element that doesn't pass your condition. You could just use

dataArray.map((ele, i) => {
  if(i === currentElement){
    return (
      <div>{element.data}</div>
    )
}

and the map will simply do nothing with any element that does not pass the condition.

Mapping over an array in React is usually (often?) used for creating <li> tags, and React might get cranky in your console about not having a key. If you see that, check out this link here: https://reactjs.org/docs/lists-and-keys.html

Upvotes: 3

Related Questions