How can I pass props from Gatsby layout to children (for example a Header component)?
import React from "react";
export default ({ children }) => {
return <div>{children()}</div>;
};
The resources I found use the following format:
{ props.children({ ...props, foo: true }) }
{ this.props.children({...this.props, updateLayoutFunction }) }
But since there is no props
, but only children, I can't get this to work. I tried this, but it also didn't work:
{ children({ foo: true }) }
In all cases, I get this error: TypeError: undefined is not an object (evaluating 'history.listen')
https://github.com/gatsbyjs/gatsby/issues/3412#event-1446894145 https://github.com/gatsbyjs/gatsby/issues/2112
Passing Props to Children in React Using the Context APIContext allows you to pass props down to an entire tree of components. It is extremely useful because you have an App component at the top but want to pass down an event handler to a child component at the bottom of the tree.
As you have seen, props enable you to pass values from one component to another component down the component tree. In the previous example, it was only a string variable. But props can be any JavaScript data type from integers over objects to arrays.
Layout components are for sections of your site that you want to share across multiple pages. For example, Gatsby sites will commonly have a layout component with a shared header and footer. Other common things to add to layouts are a sidebar and/or navigation menu.
But there are props, you're just not passing them to children.
In your layout file, instead of:
export default ({ children }) // ... etc
do
export default (props) {
const myOwnProperties = { foo: true };
return (
{props.children({ ...props, ...myOwnProperties })}
);
}
You see, the props are passed automatically until you add your own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With