1

In a functional component I want to access props inherited from the parent functional component. To get an idea what I mean, I have the following snippet:

function MainApp(props) {
    const { classes } = props;
    const [content, setContent] = useState("");

    return (
        <div className={classes.root}>
            <AppBar position="fixed" className={classes.appBar}>
                <Toolbar className={classes.toolbar}>
                    <Typography variant="title" color="inherit" fontWeight="bold">
                        CashCo
                    </Typography>
                    <ToolbarActions className={classes.toolbarActions} />
                </Toolbar>
            </AppBar>
            <main className={classes.appContent}>
                <PageContent content={content} />
            </main>
        </div>
    );
}

function App(props) {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MainApp />}></Route>
            </Routes>
        </BrowserRouter>
    );
}

I want to pass the props argument in the App() function to the MainApp(), such that I don't have to access properties like props.props.some_property. How can I do that correctly? Cause passing props like this <MainApp props={props} /> means I have to access the properties like props.props.some_property in MainApp(), that's not what I want. I want to access the props like props.some_property in MainApp().

2 Answers 2

3

You can spread the App props onto MainApp, this will let you access them like so props.classes.

function App(props) {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MainApp {...props} />}></Route>
            </Routes>
        </BrowserRouter>
    );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes it works, thank you! Can you provide me a reference to the React's official documentation please, or is it common sense?
@AndaluZ you have to think about props as an object, so each time you're passing a specific value you're actually creating a property on the props object. The spread operator can be used to copy properties from object A into object B, this behaviour has nothing to do with React :)
They do however cover it in the documentation.
1

Try like this

function App(props) {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MainApp {...props}/>}></Route>
            </Routes>
        </BrowserRouter>
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.