So right now, in my App file I have this:
{items.map(el => (
<Item
prop1={foo}
prop2={bar}
el={baz}
/>
))}
And in the <Item>
component, I have this:
<span className={finishedClass ? "finishedItem" : ""}>
{props.el}
</span>
where finishedClass
is a state variable.
So my question is, how can I check if finishedClass
is true for every single <Item>
component that gets generated as a result of the items.map
?
CodePudding user response:
So, you basically want to know if all the finishedClass
state values in all the Item
components are true. This can be simplified in the sense that if any of the Item components have finishedClass
as false, you will perform a certain action.
So, what you can do is, pass a function as a prop to the Item
component as follows:
{items.map(el => (
<Item
prop1={foo}
prop2={bar}
el={baz}
setFinishedClassToFalse={()=>{/*your statements*/}}
/>
))}
This function setFinishedClassToFalse
will be called by the Item
component if and only if its state value finishedClass
is false. Obviously, there's a little more implementation to this than what I have described. But this should give you a start.
CodePudding user response:
Parent component can communication with child component with parent props that have function in it. You can see code below onFinished
property in Parent component has handleFinished()
function value in it. That fucntion will be a bridge to help Child component to communicate with Parent component. On the Child component you must run onFinished
props to triggering handleFinished
function on Parent comoponent. In code below the trigger for props.onFinished is when <span>
clicked by user.
import React from "react";
import ReactDOM from "react-dom";
import { Grid } from "react-flexbox-grid";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { data: "test" };
}
render() {
const items = ["red", "green", "blue"];
const handleFinished = (e, index) => {
this.setState({ data: e });
console.log(this.state);
};
return (
<Grid>
{items.map((el, index) => (
<Child
prop1={"test"}
prop2={"test1"}
el={el}
onFinished={(e) => handleFinished(e, index)}
/>
))}
<div>{this.state.data.toString()}</div>
</Grid>
);
}
}
const Child = (props) => {
// example for your finishedClass value state
const finishedClass = true;
return (
<span
onClick={() => props.onFinished(finishedClass)}
className={finishedClass ? "finishedItem" : ""}
>
{props.el}{" "}
</span>
);
};
ReactDOM.render(<App />, document.getElementById("container"));
CodePudding user response:
As finishedClass is a state variable, if you just console.log(finishedClass) inside component it will just do the work