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

import React, { useState } from 'react';

import Navigation from './Navigation';
import Profile from './Profile';

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

  return (
    <div className="App">
      <Navigation name={name} />
      <hr />
      <Profile name={name} setName={setName} />
    </div>
  );
}

export default App;

Profile.js:

import React from 'react';

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

export default Profile;

Navigation.js:

import React from 'react';

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

export default Navigation;

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

Try the following:

context.js

import React from 'react';

export default React.createContext();

App.js

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

import './styles.css';
import Profile from './components/Profile';
import Navigation from './components/Navigation';
import UserProfileContext from './context';

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

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

export default App;

components/Navigation.js

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

import UserProfileContext from '../context';

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

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

  return (
    <div className="App">
      <div className="wrapper">
        <nav className="siteNavigation_nav_links">
          <div className="clubLogo landing" style={divStyle}>
            <b>Soccer</b>
          </div>

          <NavLink className="mobile_register_link" to="/profile">
            Profile
          </NavLink>

          <div className="profileImage nav menu">
            <span>{data.name}</span> | <img alt="" src={data.photo} />
          </div>
        </nav>
      </div>
    </div>
  );
};

export default Navigation;

components/Profile.js

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

import UserProfileContext from '../context';

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

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

export default Profile;

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 Context
const AppContext = React.createContext()

// Define initial state
const initialState = {}

// Define Reducer
const Reducer = (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 hook
const [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"