Home > Back-end >  Need to change a state variable within another component in React
Need to change a state variable within another component in React

Time:01-11

I need to change the value mainPageView inside the UserProfile and ChangePassword Components how to achieve that? In further I want to change mainPageView value to false when clicking a button inside the UserProfile and change it to true when clicking a button inside the ChangePassword. Here is my code

import * as React from "react";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemText from "@mui/material/ListItemText";
import ListItemAvatar from "@mui/material/ListItemAvatar";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import Typography from "@mui/material/Typography";
import HomeIcon from "@mui/icons-material/Home";
import CakeIcon from "@mui/icons-material/Cake";
import Axios from "axios";
import { useState, useEffect, useContext } from "react";
import { LoginContext, UserContext } from "../../../Helper/UserContext";
import { Button } from "@mui/material";
import UserProfile from "./Profile";
import ChangePassword from "./Profile";

export default function MainProfile() {
  const { cookies } = useContext(LoginContext);
  const employee_id = cookies.emp_id;

  const [mainPageView, setMainPageView] = useState(true);

  return (
    <div>
      {mainPageView && <UserProfile />}
      {!mainPageView && <ChangePassword />}
    </div>
  );
}

A solution (code snippet) which describes the USerProfile and ChangePassword Component

CodePudding user response:

Pass parent method as a props e.g.

 {mainPageView && <UserProfile  updatevalue ={setMainPageView}/>}
 {!mainPageView && <ChangePassword updatevalue ={setMainPageView} />}
 
 
 
 
 const ChangePassword = (props) => {
  return (
    <div>
    <h1 onClick= { () =>
        props.updatevalue(false>)
      }
      > Something</h1>
    </div>
  )

}
export default ChangePassword;
  • Related