Next.JS — getInitialProps to pass props and state to child components via ContextProviderPass props to parent component in React.jsreact-router - pass props to handler componentWhat is the difference between state and props in React?Passing AJAX Results As Props to Child ComponentHow to pass props to this.props.childrenPassing props to components when using async routingReact-redux tutorial : Where does children come fromPassing onClick function as props to child component and using it to change parent component statenext.js pass props from HOC to child components getInitialPropsCant passing props via React Router

What reasons are there for a Capitalist to oppose a 100% inheritance tax?

What is a clear way to write a bar that has an extra beat?

Doing something right before you need it - expression for this?

Is it legal for company to use my work email to pretend I still work there?

How to model explosives?

How can I make my BBEG immortal short of making them a Lich or Vampire?

What is going on with Captain Marvel's blood colour?

Why is Collection not simply treated as Collection<?>

Why doesn't H₄O²⁺ exist?

I Accidentally Deleted a Stock Terminal Theme

Why is the 'in' operator throwing an error with a string literal instead of logging false?

What is the word for reserving something for yourself before others do?

Can one be a co-translator of a book, if he does not know the language that the book is translated into?

Memorizing the Keyboard

How could indestructible materials be used in power generation?

How to take photos in burst mode, without vibration?

Intersection of two sorted vectors in C++

Did Shadowfax go to Valinor?

I'm flying to France today and my passport expires in less than 2 months

Were any external disk drives stacked vertically?

Why can't we play rap on piano?

Can a rocket refuel on Mars from water?

What to put in ESTA if staying in US for a few days before going on to Canada

Why does Arabsat 6A need a Falcon Heavy to launch



Next.JS — getInitialProps to pass props and state to child components via ContextProvider


Pass props to parent component in React.jsreact-router - pass props to handler componentWhat is the difference between state and props in React?Passing AJAX Results As Props to Child ComponentHow to pass props to this.props.childrenPassing props to components when using async routingReact-redux tutorial : Where does children come fromPassing onClick function as props to child component and using it to change parent component statenext.js pass props from HOC to child components getInitialPropsCant passing props via React Router






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am using getInitialProps() in _App.js to grab some api data and I want to pass that data down as props to my other components via React Context. I want to initialize the Context Provider with state via the constructor.



First I initialize context via createContext().



config/Context.js:






import createContext from 'react';
const Context = createContext();
export default Context;





Then I create Context.Provider in its own component using constructor to initialize state.



provider/ContextProvider.js:






import React, Component from 'react';
import Context from '../config/Context';

class ContextProvider extends Component
constructor(props)
super(props);

this.state =
filters:
active: true,
headerActive: false

;


render()
return (
<Context.Provider>
this.props.children
</Context.Provider>
);



export default ContextProvider;





In _app.js I make an API call within getInitialProps() and pass that data into the Context Provider.



pages/_app.js






import App, Container from 'next/app';
import ContextProvider from '../provider/ContextProvider';
import fetch from 'isomorphic-unfetch';

export default class MyApp extends App
static async getInitialProps()
const res = await fetch('https://node-hnapi.herokuapp.com/news');
let data = await res.json();

console.log(data)
return articles: data


render ()
const Component, pageProps = this.props;

return (
<Container>
<ContextProvider value= articles: this.props.articles>
<Component ...pageProps />
</ContextProvider>
</Container>
);






At this point I assume that I would have access to context via Context.Consumer or a hook like useContext() but context is undefined in the following component:



components/ArticleList.js:






import React from 'react';
import Context from '../config/Context';

const ArticleList = () =>
const generateArticles = () =>
const context = React.useContext(Context);
console.log(context, 'context') // Context is undefined here
// return context.articles.map(article => <p>article.title</p>)
// Error: Cannot read property 'articles' because context is undefined


return (
<div>
<h3>Article List</h3>
generateArticles()
</div>
);
;

export default ArticleList;





Why is context undefined in components/ArticleList.js? I tried passing context into the component via Context.Consumer and I got the same result.



Here is repo replicating the issue: https://github.com/joelhoelting/next-context-api-test










share|improve this question






























    0















    I am using getInitialProps() in _App.js to grab some api data and I want to pass that data down as props to my other components via React Context. I want to initialize the Context Provider with state via the constructor.



    First I initialize context via createContext().



    config/Context.js:






    import createContext from 'react';
    const Context = createContext();
    export default Context;





    Then I create Context.Provider in its own component using constructor to initialize state.



    provider/ContextProvider.js:






    import React, Component from 'react';
    import Context from '../config/Context';

    class ContextProvider extends Component
    constructor(props)
    super(props);

    this.state =
    filters:
    active: true,
    headerActive: false

    ;


    render()
    return (
    <Context.Provider>
    this.props.children
    </Context.Provider>
    );



    export default ContextProvider;





    In _app.js I make an API call within getInitialProps() and pass that data into the Context Provider.



    pages/_app.js






    import App, Container from 'next/app';
    import ContextProvider from '../provider/ContextProvider';
    import fetch from 'isomorphic-unfetch';

    export default class MyApp extends App
    static async getInitialProps()
    const res = await fetch('https://node-hnapi.herokuapp.com/news');
    let data = await res.json();

    console.log(data)
    return articles: data


    render ()
    const Component, pageProps = this.props;

    return (
    <Container>
    <ContextProvider value= articles: this.props.articles>
    <Component ...pageProps />
    </ContextProvider>
    </Container>
    );






    At this point I assume that I would have access to context via Context.Consumer or a hook like useContext() but context is undefined in the following component:



    components/ArticleList.js:






    import React from 'react';
    import Context from '../config/Context';

    const ArticleList = () =>
    const generateArticles = () =>
    const context = React.useContext(Context);
    console.log(context, 'context') // Context is undefined here
    // return context.articles.map(article => <p>article.title</p>)
    // Error: Cannot read property 'articles' because context is undefined


    return (
    <div>
    <h3>Article List</h3>
    generateArticles()
    </div>
    );
    ;

    export default ArticleList;





    Why is context undefined in components/ArticleList.js? I tried passing context into the component via Context.Consumer and I got the same result.



    Here is repo replicating the issue: https://github.com/joelhoelting/next-context-api-test










    share|improve this question


























      0












      0








      0








      I am using getInitialProps() in _App.js to grab some api data and I want to pass that data down as props to my other components via React Context. I want to initialize the Context Provider with state via the constructor.



      First I initialize context via createContext().



      config/Context.js:






      import createContext from 'react';
      const Context = createContext();
      export default Context;





      Then I create Context.Provider in its own component using constructor to initialize state.



      provider/ContextProvider.js:






      import React, Component from 'react';
      import Context from '../config/Context';

      class ContextProvider extends Component
      constructor(props)
      super(props);

      this.state =
      filters:
      active: true,
      headerActive: false

      ;


      render()
      return (
      <Context.Provider>
      this.props.children
      </Context.Provider>
      );



      export default ContextProvider;





      In _app.js I make an API call within getInitialProps() and pass that data into the Context Provider.



      pages/_app.js






      import App, Container from 'next/app';
      import ContextProvider from '../provider/ContextProvider';
      import fetch from 'isomorphic-unfetch';

      export default class MyApp extends App
      static async getInitialProps()
      const res = await fetch('https://node-hnapi.herokuapp.com/news');
      let data = await res.json();

      console.log(data)
      return articles: data


      render ()
      const Component, pageProps = this.props;

      return (
      <Container>
      <ContextProvider value= articles: this.props.articles>
      <Component ...pageProps />
      </ContextProvider>
      </Container>
      );






      At this point I assume that I would have access to context via Context.Consumer or a hook like useContext() but context is undefined in the following component:



      components/ArticleList.js:






      import React from 'react';
      import Context from '../config/Context';

      const ArticleList = () =>
      const generateArticles = () =>
      const context = React.useContext(Context);
      console.log(context, 'context') // Context is undefined here
      // return context.articles.map(article => <p>article.title</p>)
      // Error: Cannot read property 'articles' because context is undefined


      return (
      <div>
      <h3>Article List</h3>
      generateArticles()
      </div>
      );
      ;

      export default ArticleList;





      Why is context undefined in components/ArticleList.js? I tried passing context into the component via Context.Consumer and I got the same result.



      Here is repo replicating the issue: https://github.com/joelhoelting/next-context-api-test










      share|improve this question
















      I am using getInitialProps() in _App.js to grab some api data and I want to pass that data down as props to my other components via React Context. I want to initialize the Context Provider with state via the constructor.



      First I initialize context via createContext().



      config/Context.js:






      import createContext from 'react';
      const Context = createContext();
      export default Context;





      Then I create Context.Provider in its own component using constructor to initialize state.



      provider/ContextProvider.js:






      import React, Component from 'react';
      import Context from '../config/Context';

      class ContextProvider extends Component
      constructor(props)
      super(props);

      this.state =
      filters:
      active: true,
      headerActive: false

      ;


      render()
      return (
      <Context.Provider>
      this.props.children
      </Context.Provider>
      );



      export default ContextProvider;





      In _app.js I make an API call within getInitialProps() and pass that data into the Context Provider.



      pages/_app.js






      import App, Container from 'next/app';
      import ContextProvider from '../provider/ContextProvider';
      import fetch from 'isomorphic-unfetch';

      export default class MyApp extends App
      static async getInitialProps()
      const res = await fetch('https://node-hnapi.herokuapp.com/news');
      let data = await res.json();

      console.log(data)
      return articles: data


      render ()
      const Component, pageProps = this.props;

      return (
      <Container>
      <ContextProvider value= articles: this.props.articles>
      <Component ...pageProps />
      </ContextProvider>
      </Container>
      );






      At this point I assume that I would have access to context via Context.Consumer or a hook like useContext() but context is undefined in the following component:



      components/ArticleList.js:






      import React from 'react';
      import Context from '../config/Context';

      const ArticleList = () =>
      const generateArticles = () =>
      const context = React.useContext(Context);
      console.log(context, 'context') // Context is undefined here
      // return context.articles.map(article => <p>article.title</p>)
      // Error: Cannot read property 'articles' because context is undefined


      return (
      <div>
      <h3>Article List</h3>
      generateArticles()
      </div>
      );
      ;

      export default ArticleList;





      Why is context undefined in components/ArticleList.js? I tried passing context into the component via Context.Consumer and I got the same result.



      Here is repo replicating the issue: https://github.com/joelhoelting/next-context-api-test






      import createContext from 'react';
      const Context = createContext();
      export default Context;





      import createContext from 'react';
      const Context = createContext();
      export default Context;





      import React, Component from 'react';
      import Context from '../config/Context';

      class ContextProvider extends Component
      constructor(props)
      super(props);

      this.state =
      filters:
      active: true,
      headerActive: false

      ;


      render()
      return (
      <Context.Provider>
      this.props.children
      </Context.Provider>
      );



      export default ContextProvider;





      import React, Component from 'react';
      import Context from '../config/Context';

      class ContextProvider extends Component
      constructor(props)
      super(props);

      this.state =
      filters:
      active: true,
      headerActive: false

      ;


      render()
      return (
      <Context.Provider>
      this.props.children
      </Context.Provider>
      );



      export default ContextProvider;





      import App, Container from 'next/app';
      import ContextProvider from '../provider/ContextProvider';
      import fetch from 'isomorphic-unfetch';

      export default class MyApp extends App
      static async getInitialProps()
      const res = await fetch('https://node-hnapi.herokuapp.com/news');
      let data = await res.json();

      console.log(data)
      return articles: data


      render ()
      const Component, pageProps = this.props;

      return (
      <Container>
      <ContextProvider value= articles: this.props.articles>
      <Component ...pageProps />
      </ContextProvider>
      </Container>
      );






      import App, Container from 'next/app';
      import ContextProvider from '../provider/ContextProvider';
      import fetch from 'isomorphic-unfetch';

      export default class MyApp extends App
      static async getInitialProps()
      const res = await fetch('https://node-hnapi.herokuapp.com/news');
      let data = await res.json();

      console.log(data)
      return articles: data


      render ()
      const Component, pageProps = this.props;

      return (
      <Container>
      <ContextProvider value= articles: this.props.articles>
      <Component ...pageProps />
      </ContextProvider>
      </Container>
      );






      import React from 'react';
      import Context from '../config/Context';

      const ArticleList = () =>
      const generateArticles = () =>
      const context = React.useContext(Context);
      console.log(context, 'context') // Context is undefined here
      // return context.articles.map(article => <p>article.title</p>)
      // Error: Cannot read property 'articles' because context is undefined


      return (
      <div>
      <h3>Article List</h3>
      generateArticles()
      </div>
      );
      ;

      export default ArticleList;





      import React from 'react';
      import Context from '../config/Context';

      const ArticleList = () =>
      const generateArticles = () =>
      const context = React.useContext(Context);
      console.log(context, 'context') // Context is undefined here
      // return context.articles.map(article => <p>article.title</p>)
      // Error: Cannot read property 'articles' because context is undefined


      return (
      <div>
      <h3>Article List</h3>
      generateArticles()
      </div>
      );
      ;

      export default ArticleList;






      javascript reactjs next.js






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 21 at 22:14







      Joel Hoelting

















      asked Mar 21 at 22:03









      Joel HoeltingJoel Hoelting

      484420




      484420






















          1 Answer
          1






          active

          oldest

          votes


















          1














          In ContextProvider.js you forget to pass value to Context.Provider



          import React, Component from 'react';
          import Context from '../config/Context';

          class ContextProvider extends Component
          constructor(props)
          super(props);

          this.state =
          filters:
          active: true,
          headerActive: false

          ;


          render()
          const value = this.props
          return (
          <Context.Provider value= value >
          this.props.children
          </Context.Provider>
          );



          export default ContextProvider;





          share|improve this answer























          • Thank You! I completely missed that.

            – Joel Hoelting
            Mar 22 at 14:32












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55289944%2fnext-js-getinitialprops-to-pass-props-and-state-to-child-components-via-conte%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          In ContextProvider.js you forget to pass value to Context.Provider



          import React, Component from 'react';
          import Context from '../config/Context';

          class ContextProvider extends Component
          constructor(props)
          super(props);

          this.state =
          filters:
          active: true,
          headerActive: false

          ;


          render()
          const value = this.props
          return (
          <Context.Provider value= value >
          this.props.children
          </Context.Provider>
          );



          export default ContextProvider;





          share|improve this answer























          • Thank You! I completely missed that.

            – Joel Hoelting
            Mar 22 at 14:32
















          1














          In ContextProvider.js you forget to pass value to Context.Provider



          import React, Component from 'react';
          import Context from '../config/Context';

          class ContextProvider extends Component
          constructor(props)
          super(props);

          this.state =
          filters:
          active: true,
          headerActive: false

          ;


          render()
          const value = this.props
          return (
          <Context.Provider value= value >
          this.props.children
          </Context.Provider>
          );



          export default ContextProvider;





          share|improve this answer























          • Thank You! I completely missed that.

            – Joel Hoelting
            Mar 22 at 14:32














          1












          1








          1







          In ContextProvider.js you forget to pass value to Context.Provider



          import React, Component from 'react';
          import Context from '../config/Context';

          class ContextProvider extends Component
          constructor(props)
          super(props);

          this.state =
          filters:
          active: true,
          headerActive: false

          ;


          render()
          const value = this.props
          return (
          <Context.Provider value= value >
          this.props.children
          </Context.Provider>
          );



          export default ContextProvider;





          share|improve this answer













          In ContextProvider.js you forget to pass value to Context.Provider



          import React, Component from 'react';
          import Context from '../config/Context';

          class ContextProvider extends Component
          constructor(props)
          super(props);

          this.state =
          filters:
          active: true,
          headerActive: false

          ;


          render()
          const value = this.props
          return (
          <Context.Provider value= value >
          this.props.children
          </Context.Provider>
          );



          export default ContextProvider;






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 22 at 11:47









          evgeni fotiaevgeni fotia

          2,2572418




          2,2572418












          • Thank You! I completely missed that.

            – Joel Hoelting
            Mar 22 at 14:32


















          • Thank You! I completely missed that.

            – Joel Hoelting
            Mar 22 at 14:32

















          Thank You! I completely missed that.

          – Joel Hoelting
          Mar 22 at 14:32






          Thank You! I completely missed that.

          – Joel Hoelting
          Mar 22 at 14:32




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55289944%2fnext-js-getinitialprops-to-pass-props-and-state-to-child-components-via-conte%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현