0

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.

2 Answers 2

3

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

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

Comments

2

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>);
}

1 Comment

element could be undefined. A check should be added to return null in that case, so that it won't throw an exception.

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.