I'm trying to make a sidebar menu without lib and I got a problem.
I have a function used for setState, but it only works with JSX
in return
, when I render the menu and pass this function, it is run but setState
not working in it.
Hear is my code:
export default function DropdownSideMenu(props) {
const [state, setState] = useState({});
const renderDropdownMenu = (data) => {
return data.map((item) => {
if (item.child.length >= 1) {
return (
//THIS IS NOT WORKING, doSomeThing run but state not change.
<li key={item.id} onClick={() => doSomeThing(item.value)}>
<NavLink to={item.link}>{v[item.name]}</NavLink>
<ul>{renderDropdownMenu(item.child)}</ul>
</li>
);
}
return (
<li key={item.id}>
<NavLink to={item.link}>{v[item.name]}</NavLink>
</li>
);
});
};
const doSomeThing = (value) => {
console.log(value);
setState(value);
};
return (
<ul>
{renderDropdownMenu(props.data)}
{/* THIS IS WORKING, doSomeThing run well */}
<li onClick={() => doSomeThing(value)}>
<NavLink to="/">Test</NavLink>
</li>
</ul>
);
}
UPDATE: Problem-solve I found a big mistake in the project, when project building, I make a Layout component and PUT IT INTO CONTAINER COMPONENT, this is the wrong way because when we struggle Sidebar in Layout component Router will re-render the container and make Layout re-render so Sidebar can not make action setState.
I FIXED BY PUT LAYOUT INTO APP COMPONENT and WRAP ALL CONTAINER INSIDE LAYOUT COMPONENT, it works fine.
P/s: If someone see another mistake, please mention it in the comments. Thanks you so much.