0
votes

i want to access props in the react functional component using react and typescript.

I have the MainComponent which has Layout component and i pass prop isOpen to Layout component from MainComponent like in below code,

const Layout: React.FC = ({children}) => ( //how to access isOpen prop here
    <>
        <leftNav />
            {children}
        <RightNav isOpen={isOpen} />
    </>
);
interface Props {
    item: item;
}
function Main({ item }: Props) {
    return (
        <Wrapper>
            <Switch>
                <Route
                    path="/items"
                    render={routeProps => (
                        <Layout isOpen={isOpen}> //passing prop here
                            <Items />
                        </Layout>
                   )}
                />
            </Switch>
        </Wrapper>
    )
}

I have tried to access it like below

interface Props {
    children: any;
    isOpen: boolean;
}
const Layout: React.FC = ({children, isOpen}: Props) => (
    <>
        <leftNav />
            {children}
        <RightNav isOpen={isOpen} />
    </>
);

But the above throws error jsxelement is not assignable to type FC component.

could someone help me fix this. thanks.

2

2 Answers

0
votes

You need to type the props for the FC generic:

//interface Props { ... }

const Layout: React.FC<Props> = ({children, isOpen}) => (
    <>
        <leftNav />
            {children}
        <RightNav isOpen={isOpen} />
    </>
);

or omit the FC altogether:

//interface Props { ... }

const Layout: ({children, isOpen}: Props) => (
    <>
        <leftNav />
            {children}
        <RightNav isOpen={isOpen} />
    </>
);
0
votes

React.FC is generic and takes a type argument for the props. You can write your layout component like this.

interface Props {
    isOpen: boolean; 
    // if you want isOpen props to be optional
    // isOpen?: boolean;
}

const Layout: React.FC<Props> = ({children, isOpen}) => (
    <>
        <leftNav />
            {children}
        <RightNav isOpen={isOpen} />
    </>
);

Your main component is fine.