Trying to figure out how to transfer data between siblings components. The idea is this: you need to make sure that only one child component has an "active" class (Only one div could be selected). Here is the code: https://codepen.io/slava4ka/pen/rNBoJGp
import React, {useState, useEffect} from 'react';
import styleFromCss from './Garbage.module.css';
const ChildComponent = (props) => {
const [style, setStyle] = useState(`${styleFromCss.childComponent}`);
const [active, setActive] = useState(false)
const setActiveStyle = () => {
console.log("setActiveStyle");
if (!active) {
setStyle(`${styleFromCss.childComponent} ${styleFromCss.active}`)
setActive(true)
} else {
setStyle(`${styleFromCss.childComponent}`);
setActive(false)
}
};
//console.log(props);
console.log(`id ${props.id} style ${style}`);
return (
<div className={style} onClick={() => {
props.updateData(props.id, () => setActiveStyle())
}}>
<h3>{props.name}</h3>
</div>
)
};
const ParentComponent = (props) => {
const state = [{'id': 0, 'name': 'один'}, {'id': 1, 'name': 'два'}, {'id': 2, 'name': 'три'}];
const [clicked, setClicked] = useState(null);
const highlight = (id, makeChildActive) => {
//console.log("click! " + id);
setClicked(id);
makeChildActive();
};
return (
<div>
{state.map(entity => <ChildComponent updateData={highlight}
key={entity.id}
id={entity.id}
name={entity.name}
isActive={(entity.id ===
clicked) ? styleFromCss.active : null}
/>)}
</div>
)
};
export default ParentComponent;
styleFromCss.module.css:
.childComponent{
width: 200px;
height: 200px;
border: 1px solid black;
margin: 10px;
float: left;
text-align: center;
}
.active{
background-color: blueviolet;
}
I tried to implement this through hooks, not classes. As a result, when you click on the selected component, its classes change, and nothing happens on its siblings. As I understand it, they simply do not redraw. The question is how to fix it? And is such an approach correct for the realization of a given goal? Or my idea is fundamentally wrong, I will be grateful for the advice)))