Reputation: 49
Say I have a header component, which will be reused on every single page within my site. Is there a way to pass the same props to every instance of this Header component, without having to explicitly type out the props on every instance?
For example, suppose I have a home page and a /proposecourse page. Both of these pages have the "main" component, and also a header component, like so:
<Route path="/proposecourse">
<Header />
<Proposals />
</Route>
<Route exact path="/">
<Header
mysky={mysky}
loggedIn={loggedIn}
setLoggedIn={setLoggedIn}
setSkynetID={setSkynetID}
/>
<Home />
</Route>
As can be seen, the second instance of Header
has many props passed to it. But the first Header
, although the same component, does not have those props, and I cannot access them on that specific component. Is there an efficient way of passing the same props to both without retyping the code?
Upvotes: 0
Views: 35
Reputation: 84902
You can save the element to a local variable, and then use that multiple times in the rendering:
const Example = () => {
const header = (
<Header
mysky={mysky}
loggedIn={loggedIn}
setLoggedIn={setLoggedIn}
setSkynetID={setSkynetID}
/>
);
return (
<>
<Route path="/proposecourse">
{header}
<Proposals />
</Route>
<Route exact path="/">
{header}
<Home />
</Route>
</>
);
};
Upvotes: 1
Reputation: 1858
You can use a spread operator to avoid explicitly typing the props.
const myProps = {
mysky,
loggedIn,
setLoggedIn,
setSkynetID,
};
<Header {...myProps} />
Upvotes: 0