Im trying to add numbers to an array in the parent from the child component . when i try to send data only based on a random number it seems that the numbers are confused . (the game im trying to bulid is Lights Out)
Parent :
import "./App.css";
import Square from "./Square";
import react, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
lightNums: [],
};
}
showNum(n) {
this.setState((st) => ({
lightNums: [...st.lightNums, n],
}));
}
arr = Array.from({ length: 25 }).map((e, g) => {
return <Square num={g} key={g} showNum={this.showNum.bind(this)} />;
});
render() {
return <div className="App">{this.arr}</div>;
}
}
export default App;
And the child :
import react, { Component } from "react";
import "./Square.css";
class Square extends Component {
constructor(props) {
super(props);
this.clickHandler = this.clickHandler.bind(this);
this.state = {
clicked: this.rand(this.props.num),
};
}
clickHandler(e) {
this.props.showNum(this.props.num);
this.setState((st) => ({ clicked: st.clicked ? false : true }));
}
rand = (num) => {
const rand = Math.floor(Math.random() * 2);
if (rand === 1)
{
this.props.showNum(num);
return true;
}
else {
return false;
}
};
classN = () => `square ${this.state.clicked ? "clicked" : ""}`;
render() {
return (
<div className={this.classN()} onClick={this.clickHandler}>
{this.props.num}
</div>
);
}
}
export default Square;
(if the random number is 1 , run the function on the parent that add the number to array) And you can see that when i run it the array is not based on the true or false, it is just adding numbers : (supposed to show only the light colors in the array..)
You would create an addNumber method in the parent, and pass it to the child as a prop. User, interacting with the child, calls the addNumber, pushing the new value to the parent.
Function based components are a better way to do all of this, as opposed to the legacy class based components.
You can pass a method from your parent component to the child component as props.
Here simple example:
const { useState, useCallback } = React;
function Child({ onChange }) {
return <input type="text" onChange={(e) => onChange(e.target.value)} />;
}
function App() {
const [name, setName] = React.useState("");
const handleClick = useCallback((e) => {
setName(e);
}, []);
return (
<div>
<div>{name}</div>
<Child onChange={handleClick} />
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>