someuser2491
someuser2491

Reputation: 1978

How to render a component by looping through the array in reactjs?

i want to render a component if some condition is true and loop through that prop array.

Below is what i want to do

render() {
    return (
           {first_condition &&
               <div>some text</div>}
           {this.props.some_vars && 
               this.props.some_vars.forEach((var, index) => {
                   this.box_ref.current && var.name &&
                       <ChildComponent
                           element1={var.element1}
                           element2={var.element2}
                       />
           }//error here
       );
}

But the code gives me an error at the curly bracket...how should i render this childcomponent based on that condition. Thanks.

Upvotes: 0

Views: 384

Answers (3)

hardy
hardy

Reputation: 901

You should user .map (which is an array method in JS). This returns a new array always. It also returns immutable things, which are new and different from reference, it means if you change the provided array it will make no effect to the result of mapped array. As ForEach loop is mutable, this carry forward the reference.

That's why we use immutable like .map

Here, how we can use ?

        {this.props.some_vars.map(item, index) => 
            <ChildComponent
              key= {index}  //if you not pass the key it will throw warning.
              element1={item.element1}
              element2={item.element2}
            />
        }

Upvotes: 0

AKX
AKX

Reputation: 169378

  • There were bracket-related syntax errors.
  • You'll have to use map, not forEach.
  • var is a reserved keyword; use variable.
  • To return multiple sibling components in render, wrap them in a fragment (<></>).
  • You should also figure out a key for each component rendered in the loop.
function render() {
  return (
    <>
      {first_condition && <div>some text</div>}
      {this.props.some_vars &&
        this.props.some_vars.map(
          (variable, index) =>
            this.box_ref.current &&
            variable.name && (
              <ChildComponent
                element1={variable.element1}
                element2={variable.element2}
              />
            )
        )}
    </>
  );
}

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53964

You should use #Array.map instead of #Array.forEach which returns void.

Moreover:

  1. You must render a single React Node.
  2. var is a preserved keyword.
  3. You need to provide key property in React Node's array.
// </> is sugar syntax for <React.Fragment/>
<>
  {first_condition && <div>some text</div>}
  {this.props.some_vars &&
    this.props.some_vars.map(
      (value, index) =>
        this.box_ref.current &&
        value.name && (
          <ChildComponent key={index} element1={value.element1} element2={value.element2} />
        )
    )}
</>

Refer to List and Keys in React docs.

Upvotes: 0

Related Questions