C
C
CHtommy2021-09-12 00:27:44
React
CHtommy, 2021-09-12 00:27:44

How to pass state to a child element?

I can’t figure out a little how to correctly transfer callback between files ... I read the dock and watched the video and still can’t catch up ...
It is necessary to transfer hovered from parent to child. If the parent is hovered, then the child should also be activated and return the className of the
Parent:

function NavItem(props) {
 
    const [hovered, setHovered] = useState(false);
    const toggleHover = () => setHovered(!hovered);
   

    return (
        <div className={`${styles.header__nav_item} ${hovered ? ' header__nav_item_active' : ''}`} onMouseEnter={toggleHover} onMouseLeave={toggleHover}>
            <a className = {styles.header__nav_link} data-slug = {`${"slug-"}${props.slug}`} href = {props.url}>
                {props.title}
            </a>
        </div>
    );

} export default NavItem;

Child:
function navItemSubmenu(props) {

    return (
        <div className={`${styles.header__nav_item} ${props.hovered ? 'header__submenu_inner_active' : ''}`} data-slug = {`${"slug-"}${props.dataSlug}`} >
            <div className={styles.header__submenu_col}>
                <div className={styles.header__submenu_item}>
                    <div className={styles.header__submenu_title}>
                        <div>{props.subtitle}</div>
                    </div>
                    <div className={styles.header__submenu_list}>
                        <div className={styles.header__submenu_list_item}>
                            <a className={styles.header__submenu_list_link} href="/ministerstvo/o-ministerstve/obschie-svedeniya/">
                                Общие сведения
                            </a>
                        </div>
    );
} export default navItemSubmenu;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin, 2021-09-12
@just_konstantin

In your example, there is no use navItemSubmenuinside NavItem. But if we assume that it is used there, then it is passed like a normal one props:

function NavItem(props) {
 
    const [hovered, setHovered] = useState(false);
    const toggleHover = () => setHovered(!hovered);
   

    return (
        // остальной код
        <NavItemSubmenu hovered={hovered} />
    );

} export default NavItem;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question