Search code examples
javascriptreactjsnext.js

React how to Pass data from component to its sub-component


export const TriggerView = ({ children }: { children: React.ReactNode }) => {
    const [show, setShow] = useState(false);
    return <div>{children}</div>;
};

const Trigger = ({ children }: { children: React.ReactNode }) => {
    return <div>{children}</div>;
};

const View = ({ children }: { children: React.ReactNode }) => {
    return <div>{children}</div>;
};

TriggerView.Trigger = Trigger;
TriggerView.View = View;

I made a component TiggerView that have two sub-components Trigger and View the problem is that I want the show and setShow state to be passed to the sub-components but I don't know how


Solution

  • Np I Sloved It

    "use client";
    import React, { useEffect, useState } from "react";
    
    export const TriggerView = ({ children }: { children: React.ReactNode }) => {
        const [show, setShow] = useState(false);
        return React.Children.map(children, (child) => {
            if (React.isValidElement(child)) {
                return React.cloneElement(child, {
                    show,
                    setShow,
                } as unknown as undefined);
            }
            return child;
        });
    };
    
    const Trigger = ({
        children,
        show,
        setShow,
    }: {
        children: React.ReactNode;
        show?: boolean;
        setShow?: React.Dispatch<React.SetStateAction<boolean>>;
    }) => {
        return !show && <div onClick={() => setShow!(true)}>{children}</div>;
    };
    
    const View = ({
        children,
        show,
        setShow,
    }: {
        children: React.ReactNode;
        show?: boolean;
        setShow?: React.Dispatch<React.SetStateAction<boolean>>;
    }) => {
        return show && <div>{children}</div>;
    };
    
    TriggerView.Trigger = Trigger;
    TriggerView.View = View;