Al Ex Tsm
Al Ex Tsm

Reputation: 2102

How to read and update React Context from child with function components?

In my App component I create a context(AuthContext) and define a state(authenticated) and a method to change state(setAuthenticated):

import React, {useState} from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Home from './pages/Home.js';



export const AuthContext = React.createContext();
function App() {
  const [authenticated, setAuthenticated] = useState(true);

  return (
    <AuthContext.Provider value={{authenticated, setAuthenticated}}>
      <BrowserRouter>
        <Switch>
          <Route exact path={"/"} component={Home}  />
        </Switch>
      </BrowserRouter>
    </AuthContext.Provider>
  );
}

export default App;

From the child component(Home) I can log the value of authenticated but can not render it:

import React from 'react';
import { AuthContext } from '../App.js';

function Home(props) {
const { authenticated, setAuthenticated } = React.useContext(AuthContext);
console.log(authenticated);
console.log(setAuthenticated);

  return (
    <div>
        {authenticated}
        <button onClick={() => setAuthenticated(false)}>
          Logout
        </button>
    </div>
  );
}

export default Home;

How do I render the value of authenticated inside my child component Home?

Upvotes: 1

Views: 2082

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281606

React doesn't render Boolean, null or undefined values. Check the documentation on it here

In order to render the authenticated value you need to convert it to string

return (
    <div>
        {authenticated.toString()}
        <button onClick={() => setAuthenticated(false)}>
          Logout
        </button>
    </div>
  );

Upvotes: 2

Related Questions