3

Showing white blank screen with the use of context api in React js I'm running my code which has no errors, but when I take a trip to localhost:3000 I get a blank screen. These are the React js files in the project, If I don't use the Context-API, coding is doing great.

 App.js
import "./App.css";
import { UserContextProvider } from "./contexts/user";
import { Home } from "./pages";
function App() {
  return (
    <div className="app">
      <UserContextProvider>
        <Home />
      </UserContextProvider>
    </div>
  );
}

export default App;

    user.js
import { createContext, useState } from "react";
export const UserContext = createContext();
export const UserContextProvider = (props) => {
  const [user, setUser] = useState(null); // user value can be used anywhere

  return (
    <UserContext.Provider value={{user: [user,setUser]}}>
    {props.childern}
    </UserContext.Provider>
  );
};

 SignInBtn.js
    import React,{useContext} from "react";
    import "./style.css";
    import GoogleIcon from "@mui/icons-material/Google";
    import { signInWithGoogle } from "../../services/auth";
    import { UserContext } from "../../contexts/user";
    const icon = {
      fontSize: 14,
    };
    function SignInBtn() {
      const [user, setUser] = useContext(UserContext).user;
    
      const signInBtnClick = async () =>{
        let userBySignIn = await signInWithGoogle()
        if(userBySignIn) setUser(userBySignIn)
      }
      return (
        <div className="signInBtn" onClick={signInBtnClick}>
          <div className="btn">
          <p>Signin with&nbsp;</p>
          <GoogleIcon style={icon}/>
          </div>
        </div>
      );
    }
    
    export default SignInBtn;

3 Answers3

0

first of everything make sure your SignInBtn Component is children of Context Provider

secondly

Remove the .user from here
const [user, setUser] = useContext(UserContext).user; in SignInBtn.js Where you are taking value from UserContext.

You can do this way

const {user} = useContext(UserContext);

const [user, setUser] = user

0

Solution <>{props.children}</>

You should enclose {props.childern} in Fragments. or any other tags that do not return null in any case.

Refer to this. https://codesandbox.io/s/divine-shape-6rxws?file=/src/user.js:331-353 for the exact solution

-1

you should import React in user.js it will work

shadi rzv
  • 1
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 15 '22 at 09:43