My question is simple: How can I handle the value of two child components? Example:
I have this class, Board:
import React, { Component } from 'react';
import Square from './Square';
export default class Board extends Component {
render(){
return (
<>
<Square />
<Square />
</>
);
}
}
and this is the child component:
import React, {useState} from 'react';
const Square = (props) => {
let initStatusMessage = 'Aún no se ha clicado.'
const [count, setCount] = useState(0);
const [status, setStatus] = useState(initStatusMessage);
function handleClick(){
setCount(count + 1);
if(status === initStatusMessage){
setStatus('Veces clicado: ');
}
}
return(
<div>
<p>{status}</p>
<button onClick={() => handleClick()}>{count}</button>
</div>
);
}
export default Square;
How, instead of handling the count value for each of the children, can I handle the different values from the parent?
The parent component can take independent control of each of its children, for example through a state in the parent and a function that your children receive as a "callback" to update the state in the parent.
Something like that:
If you use a functional component (I don't know how to do it with classes) you can put the state and the click handler in the parent and pass it as props to the children, like this (I did it on a pc that doesn't have react to test , there may be something wrong, you try it and tell me anything):
the square component:
I recommend this course, it's very good: https://youtube.com/playlist?list=PLvq-jIkSeTUZ5XcUw8fJPTBKEHEKPMTKk