Reputation: 1978
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
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
Reputation: 169378
map
, not forEach
.var
is a reserved keyword; use variable
.render
, wrap them in a fragment (<></>
).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
Reputation: 53964
You should use #Array.map
instead of #Array.forEach
which returns void.
Moreover:
var
is a preserved keyword.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