i want to pass props along with routercomponent props and access it in a component using react and typescript.
i have a MainComponent which has a ChildComponent. I want to pass props namely isOpen, showdialog and hidedialog props to the ChildComponent.
Below is the code,
function MainComponent() {
render= () => {
return(
<Route
exact
path="/items"
render={routeProps => (
<Layout>
<ChildComponent
isOpen={isOpen}// how to access this
showDialog={showDialog} //how to access this
hideDialog={hideDialog} //how to access this
{...routeProps}
/>
<Layout>
)}
/>
)
}
}
function ChildComponent({ history }: RouteComponentProps) {
//some logic
}
I have tried accessing like below
interface Props {
isOpen: boolean;
showDialog: any;
hideDialog: any;
}
function ChildComponent({ history }: RouteComponentProps) {
//how to access it here...
}
I am not knowing how to access it here. could someone help me fix this. thanks.
Just continuing destructuring it. Just make sure your types are lined up.
function ChildComponent({ history, isOpen, showDialog, hideDialog }: RouteComponentProps) {
//how to access it here...
}
Remember that object you're passing into the function is an instance of React Props, so everything that is a property on the JSX is passed in the props object under the same keys.
You can define the props interface to be a combination of RouteComponentProps and ChildProps. Post that destructure them from props
interface Props {
isOpen: boolean;
showDialog: any;
hideDialog: any;
}
function ChildComponent({ history, isOpen, showDialog, hideDialog }: Props & RouteComponentProps<{}>) {
}
PS on a sidenote, a functional component doesn't have a render function so you just needed to write your MainComponent like
function MainComponent() {
return(
<Route
exact
path="/items"
render={routeProps => (
<Layout>
<ChildComponent
isOpen={isOpen}
showDialog={showDialog}
hideDialog={hideDialog}
{...routeProps}
/>
<Layout>
)}
/>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.