avijit behera
avijit behera

Reputation: 23

How to pass a state in react?

I am trying ,but facing issue,how to pass state data from one to other component ,I am new in react so please explain.Actually I don't know how to pass state in react data.Thanks in advance Trying to achieve-After login after entering value in input(of login.js),it should be appear in page1.js

  1. RouteTable.js

                 import React from 'react'
                 import { BrowserRouter, Route, Routes } from 'react-router-dom'
                 import Login from './Login'
                 import Page1 from './Page1'
                 export default function RouteTable() {
                   return (
                     <div>
                         <BrowserRouter>
                         <Routes>
                             <Route path="/" element={<Login/>}/>
                             <Route path="/login" element={<Login/>}/>
                             <Route path="/firstpage" element={<Page1/>}/>
                         </Routes>
                         </BrowserRouter>
                     </div>
                   )
                 }
    

2.Login.js

                import React,{ createContext,useState } from 'react'
                import { useNavigate } from 'react-router-dom'
                export var Credentials=createContext()
                export default function Login() {
                    let navigate=useNavigate();
                    const [data, setdata] = useState({Name:"",Email:""})
                    const [details, setDetails] = useState({})
                   const handleNameChange=(e)=>{
                    setdata({
                        Name:e.target.value,
                        Email:data.Email
                    })
                    }
                   const handleEmailChange=(e)=>{
                    setdata({
                        Name:data.Name,
                        Email:e.target.value
                    })
                    }
                const handleLogin=()=>{
                    setDetails(data)
                    navigate("/firstpage")
                    
                }
                  return (
                    <div className='text-center'>
                        <dl>
                            <dt>Name</dt>
                            <dd><input onChange={handleNameChange} type="text"/></dd>
                            <dt>Email</dt>
                            <dd><input onChange={handleEmailChange} type="text"/></dd>
                        </dl>
                     <button onClick={handleLogin}>Login</button>
                    </div>
                  )
                }
                
  1. Page1.js

                 import React from 'react'
                 import { useContext } from 'react'
                 import { Credentials } from './Login'
    
                 export default function Page1() {
                 let data=useContext(Credentials)   
                   return (
                     <div>
                         <h2 className='text-center'>Hello{data}</h2>
                         <p>Page1.Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis 
             assumenda officia impedit, tempora, ut
             delectus adipisci, cum enim quo harum dolores explicabo
             necessitatibus minima suscipit commodi animi fugit nemo ea in sequi
             atque voluptates. Earum, veritatis. Ullam eius eos similique,
             tempore maxime fuga quidem ex dolores earum voluptas, ea, sunt illum
             quis libero modi ipsum qui accusantium voluptate explicabo sed iusto
             odio? Quasi laudantium distinctio provident aliquid libero quas
             excepturi minima, eveniet quibusdam voluptate quae animi dolorem
             facilis perferendis, error nulla accusantium ex enim? Provident
             temporibus quas dolore sunt ipsam, sint placeat consequatur
             quibusdam alias? Commodi, repellat in! Fugit, voluptates?</p>
    
                     </div>
                   )
                 }
    

Upvotes: 1

Views: 53

Answers (1)

Aleksa Ristic
Aleksa Ristic

Reputation: 2499

In your case, best thing to do is to use context. Context allows you to create it at top level, and then in child component you can "catch" it if you need it, without passing anything from parent.

First create context:const MyContext = createContext()

Once context is created we need to declare it inside our app. Every other element wrapped inside that provider will be able to "catch" or use that context.

 import React from 'react'
 import { BrowserRouter, Route, Routes } from 'react-router-dom'
 import Login from './Login'
 import Page1 from './Page1'
 import MyContext from './MyContext'

 export default function RouteTable() {

   const [someState, setSomeState] = useState(null)

   return (
     <div>
         <MyContext.Provider value={someState}>
             <BrowserRouter>
             <Routes>
                 <Route path="/" element={<Login/>}/>
                 <Route path="/login" element={<Login/>}/>
                 <Route path="/firstpage" element={<Page1/>}/>
             </Routes>
             </BrowserRouter>
         </MyContext.Provider>
     </div>
   )
 }

Once we initialized MyContext and assigning it value of someState we can use that provided context in any file like this:


import MyContext from './MyContext'

export default function Page1() {

    const contextConst = useContext(MyContext)

    return (
        <div>
            {JSON.stringify(contextConst)}
        </div>
    )
}

EDIT based on comment:

If you want to bring data from child to parent, in this case (where you need user state in many components) I would just pass setSomeState function in provider along with someState like this:

// Change this
<MyContext.Provider value={someState}>
// to this
<MyContext.Provider value={ { stateValue: someState, setStateFunction: setSomeState } }>

You can see we set value as object which have two properties, stateValue which holds our state and setStateFunction which we can use to change state

Now in child we catch context and use that setStateFunction

import MyContext from './MyContext'

export default function Page1() {

    const contextConst = useContext(MyContext)

    return (
        <div>
            Our state object: {JSON.stringify(contextConst.stateValue)}
        </div>
        <button onClick={() => { contextConst.setStateFunction({ something: 'something' }) }}>
            CLick me
        </button>
    )
}

There are more ways of passing values from child to parent, but for this case I think this will be the best.

Others ways are using forwardRef in combination with useImperativeHandle hook where you can expose some functions from child to parent, and so you can return values or do stuff inside that child function and call it from parent to retrieve that value or do stuff.

Upvotes: 1

Related Questions