Home > other >  How to use context in different component
How to use context in different component

Time:05-30

This is my private route component

import React, { useEffect, useState, createContext } from "react";
import Header from "../../components/common/Header/container";
import { Outlet, useNavigate, Navigate } from "react-router-dom";

const PrivateRoute=({ fetchMe })=> {
  const [type, setType] = useState("sports_keymoments");
  const isAuthenticated = localStorage.getItem("authToken");
  const [lodar, setLodar] = useState(true);
  const [user, setUser] = useState({ name: "Ashish" });
  const { Provider } = createContext('user');

  return isAuthenticated ? (
    <>
      <Provider user={user}>
        {lodar && <Spin indicator={antIcon} className="loader__full" />}
        <Header type={type} setType={setType} />
        <Outlet context={[type, setType]} />
      </Provider>
    </>
  ) : (
    <Navigate to="/login" />
  );
}
export default PrivateRoute;

Now I need to use user context in the Header and the outlet component. For that I did this

const theme = useContext("user");
console.log({theme})

But I am getting undefined in the theme. Kindly help with this.

CodePudding user response:

You should write <Provider value={user}> instead of <Provider user={user}>

Context.Provider documentation

You should give a look at the useContext documentation

First create the context ouside of your component and export it

export const UserContext = React.createContext({name: ""});

In your App component :

<UserContext.Provider value={user}>

In your children components :

import {UserContext} from "..."

const user = useContext(UserContext);
console.log(user.name);

CodePudding user response:

When using context you create it outside of your react component, then use it. Example files:

  • contextNews.js (Your context file)
  • ProviderWrapper.js (The wrapper for the react components which will consume your context)
  • componentUsesContext.js (An example component using the context)

contextNews.js

import React, { useState } from 'react';

// This can be whatever you want. Just an example.
const placeholder = {
  dataNews: {
    title: '',
  },
  setDataNews: () => {},
};

export const ContextNews = React.createContext(placeholder);

export const ProviderNews: React = ({ children, dataNewsDefault = {}}) => {
  const [dataNews, setDataNews] = useState(dataNewsDefault);

  return (
    <ContextNews.Provider
      value={{
        dataNews,
        setDataNews
      }}
    >
      {children}
    </ContextNews.Provider>
  );
};

ProviderWrapper.js

import {ProviderNews} from './contextNews'
import ComponentUsesContext from './ComponentUsesContext'
// You must provider a wrapper
// You cannot access context here.
const Wrapper = () => {
   <ProviderNews> {/* your components that will share context go here...*/}
      <ComponentUsesContext/> 
   </ProviderNews>
}

ComponentUsesContext.js


import {ContextNews} from './contextNews'

const Comp = () => {
  // have access to properties of the context now...
  const {dataNews, setDataNews} = React.useContext(contextNews)
  return null; // whatever you want...
}
  • Related