Skip to content Skip to sidebar Skip to footer

Pass Data Between React Hooks

How can I pass the data from one React hooks form (component) to another component. For example if I need player name and photo pass from Profile.js and make it available in Naviga

Solution 1:

Like mentioned in the comments, one option is to left your application's state up (and that should be the preferred option for simple state).

In practice, that would look like:

App.js

importReact, { useState } from'react';

importNavigationfrom'./Navigation';
importProfilefrom'./Profile';

functionApp() {
  const [name, setName] = useState('');

  return (
    <divclassName="App"><Navigationname={name} /><hr /><Profilename={name}setName={setName} /></div>
  );
}

exportdefaultApp;

Profile.js:

importReactfrom'react';

constProfile = ({ name, setName }) => {
  return (
    <><div>Profile: {name}</div><inputtype="text"name="name"value={name}onChange={e => setName(e.target.value)}
      />
    </>
  );
};

exportdefaultProfile;

Navigation.js:

importReactfrom'react';

constNavigation = ({ name }) => {
  return<div>Navigation: {name}</div>;
};

exportdefaultNavigation;

Edit: After a closer look at your code, I think using context API makes more sense in this case.

Try the following:

context.js

importReactfrom'react';

exportdefaultReact.createContext();

App.js

importReact, { useState } from'react';
import { BrowserRouter, Route, Switch } from'react-router-dom';

import'./styles.css';
importProfilefrom'./components/Profile';
importNavigationfrom'./components/Navigation';
importUserProfileContextfrom'./context';

constApp = () => {
  const [data, setData] = useState({
    id: 'player-1',
    name: 'Player One',
    age: 25,
    photo: 'rose.JPG',
  });

  return (
    <UserProfileContext.Providervalue={{data, setData }}><BrowserRouter><Navigation /><Switch><Routepath="/profile"component={Profile} /></Switch></BrowserRouter></UserProfileContext.Provider>
  );
};

exportdefaultApp;

components/Navigation.js

importReact, { useContext } from'react';
import { NavLink } from'react-router-dom';

importUserProfileContextfrom'../context';

constNavigation = () => {
  const { data } = useContext(UserProfileContext);

  const divStyle = {
    float: 'left',
    color: '#64cad8',
    padding: '0px 0px 0px 10px',
    font: 'Lucida, sans-serif',
  };

  return (
    <divclassName="App"><divclassName="wrapper"><navclassName="siteNavigation_nav_links"><divclassName="clubLogo landing"style={divStyle}><b>Soccer</b></div><NavLinkclassName="mobile_register_link"to="/profile">
            Profile
          </NavLink><divclassName="profileImage nav menu"><span>{data.name}</span> | <imgalt=""src={data.photo} /></div></nav></div></div>
  );
};

exportdefaultNavigation;

components/Profile.js

importReact, { useContext } from'react';
import { useForm } from'react-hook-form';

importUserProfileContextfrom'../context';

constProfile = () => {
  const { setData } = useContext(UserProfileContext);
  const { register, handleSubmit } = useForm();

  return (
    <div><formonSubmit={handleSubmit(setData)}><b>Profile</b><inputname="id"ref={register} /><inputname="name"ref={register} /><inputname="age"ref={register} /><buttontype="submit"className="submitButton">
          Click
        </button></form></div>
  );
};

exportdefaultProfile;

Solution 2:

You can utilize react-redux for global state handling or pass a callback function from Navigation.js to Profile.js.

Solution 3:

Use React's built in context API. Wrap your App in context provider, then you can use useContext hook to access state, dispatch state updates between components.

App level setup - one time

// Define ContextconstAppContext = React.createContext()

// Define initial stateconst initialState = {}

// Define ReducerconstReducer = (state, dispatch) => {
  switch(action.type) {
    case"ACTION_TYPE": return {...state, prop: action.payload}
    default: return state
  }
}


//Wrap main App in context, pass state from React's useReducer hookconst [state, dispatch] = useReducer(Reducer, initialState)
<AppContext.Provider data={{
  state,
  dispatch
}}>
  <ReactAppMainWrapper />
</AppContext.Provider>

Component level

const {state, dispatch} = useContext(AppContext);

// to update state call dispatch from anywhere, all components consuming state will be updated

dispatch({
   type: "ACTION_TYPE",
   payload: "new_value"
})

Explanation

The state serves as redux like store, available in the entire app.

In any component, import AppContext and use React's builtin useContext hook to interact with store from the component.

Data object passed in Context provider above is available from this.

Post a Comment for "Pass Data Between React Hooks"