1

The main application looks like this:

import Cookies from 'js-cookie';
function App() {
let cookie = Cookies.get('mycookie');
return (
    <>
        <Router>
            <div>
                {<Switch>
                    <Route path="/comp1">
                        <Comp1 />
                    </Route>
                    <Route path="/comp2">
                        <Comp2 />
                    </Route>
                </Switch>
            </div>
        </Router>
    </div>
);
}

As you can see, in the main app Im reading the cookie. Now, all the components will need to access the cookie. How can I make the components to read the cookie from the main app? Of course I could read the cookie by using "Cookies.get". But as Im doing other things in App.js than only reading the cookie, I would prefer to do operations once in App.js and then share all this with components.

3
  • 1
    You could pass them to your components directly like this <Comp1 cookie={cookie} /> and use this.props.cookie in your Comp1 Commented Sep 15, 2020 at 7:48
  • But IM not using classes. I guess the keywork "this" will not work? Commented Sep 15, 2020 at 7:49
  • 1
    If your component is a function, then it'll look like this function Comp1(props) { ... props.cookie; } Commented Sep 15, 2020 at 7:50

1 Answer 1

2

You could pass as a prop to children/descendants that need it

import Cookies from 'js-cookie';

function App() {
  let cookie = Cookies.get('mycookie');
  return (
    <div>
      <Router>
        <div>
          {<Switch>
            <Route path="/comp1">
              <Comp1 cookie={cookie} />
            </Route>
            <Route path="/comp2">
              <Comp2 />
            </Route>
          </Switch>}
        </div>
      </Router>
    </div>
  );
}

In the component access via props

const { cookie } = props;

Or you can use the Context API and create a cookie context

export const CookieContext = React.createContext();

app

import Cookies from 'js-cookie';

function App() {
  let cookie = Cookies.get('mycookie');
  return (
    <div>
      <Router>
        <div>
          <CookieContext.Provider value={cookie}>
            {<Switch>
              <Route path="/comp1">
                <Comp1 />
              </Route>
              <Route path="/comp2">
                <Comp2 />
              </Route>
            </Switch>}
          </CookieContext.Provider>
        </div>
      </Router>
    </div>
  );
}

Inside a component

import { CookieContext } from './CookieContext';

const cookie = useContext(CookieContext);
Sign up to request clarification or add additional context in comments.

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.