Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass props from layout to children in Gatsby

Tags:

reactjs

gatsby

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

like image 417
lukas Avatar asked Feb 10 '18 21:02

lukas


People also ask

Can I pass props to props children?

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.

What types of things can you pass in the props?

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.

What is layout in Gatsby?

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.


Video Answer


1 Answers

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.

like image 91
Design by Adrian Avatar answered Nov 15 '22 03:11

Design by Adrian