I am learning React and I have a problem with my childCallback, for return data from child to parent.
I make a navbar and when I click on the navButton, the parent receive the name of the precedent button, I have to click two times for display the good data.
Here is my code :
//PARENT COMPONENT
export const Profil = () => {
const [navActive, setNavActive] = useState("infos");
const handleCallback = (childData, e) => {
setNavActive(childData);
};
// View
return (
<div>
<Navbar callback={handleCallback} />
<Infos />
<Gpg />
{navActive}
</div>
);
};
//CHILD COMPONENT
export const Navbar = ({ callback }) => {
// Nav Items
let nav = [
{ key: 1, name: "infos" },
{ key: 2, name: "gpg" },
{ key: 3, name: "compte" },
{ key: 4, name: "otp" },
{ key: 5, name: "journal" },
];
// State
const [activeTitle, setActiveTitle] = useState(nav[0].name);
// Change the selected nav
function selectNav(e) {
let selected = e.target.innerText;
setActiveTitle(selected);
}
const onTrigger = () => {
callback(activeTitle);
};
// View
return (
<Nav tabs>
{nav.map((item) => (
<NavItem key={item.key} onClick={onTrigger}>
<NavLink
style={{ cursor: "pointer" }}
onClick={selectNav}
active={activeTitle === item.name}
>
{item.name}
</NavLink>
</NavItem>
))}
</Nav>
);
};
I don't know how to correct that.
Thank you in advance for your answers
CodePudding user response:
Try to remove onclick from NavItem and call your callback function from selectNav function directly.
CodePudding user response:
The problem come from the setActiveTitle(selected)
in Navbar, with console.log I test and the value is good before this.