Home > Net >  Use data in all components in react
Use data in all components in react

Time:06-12

I want to get data and update it like this

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const data = [
  {
    id: 1,
    name: "Pansy Rolling",
    email: "[email protected]",
  },
  {
    id: 2,
    name: "Klaus Hrycek",
    email: "[email protected]",
  },
  {
    id: 3,
    name: "Anabella Ellaway",
    email: "[email protected]",
  },
  {
    id: 4,
    name: "Leonard Pickless",
    email: "[email protected]",
  },
  {
    id: 5,
    name: "Loy Liddel",
    email: "[email protected]",
  },
];

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <viewAndUpdateData data={data}>
    <App />
  </viewAndUpdateData>
);

App.js

const App = () => {

  const [data, setdata] = viewAndUpdateData(data);
  return <div className="App">App js file</div>;
};

export default App;

Can anyone please help me

CodePudding user response:

// Step 1: create a file UserContext.js

//uncomment below statement in your real project
//import { createContext } from "react"; 
const {createContext,useContext} = React;   //using this method due to stackoverflow limitation
const UserContext = createContext();


//export default UserContext;  uncomment this line when you use in //seperate file. 


//Step 2: Wrap your app at root level under Context Provider 
/*

The Provider is a component that sets the data and then wraps some   child components. Any wrapped child components will have access to data from the Provider with the useContext Hook.

Since the user data will be constant across the project, put it as high up the component tree as you can. In this application, you will put it at the root level in the App component:

*/

//This data will share across all components. This is up to you how //you get this data. ie. Via api etc



function Users(){
  //const users = useContext(UserContext) you can access data here also
  //to access in JSX, you have to use Consumer
  return (
    <UserContext.Consumer>
      {
      users=>(
      
      <div> 
      {users.map((user, _) => (
            <div key={user.id}>
              <h4>{user.id}</h4>
              <h5> {user.name}</h5>
              <h6>{user.email}</h6>
            </div>
          ))}
      
      </div>)
      }
    
    </UserContext.Consumer>
   
  )
}

function App() {
const data = [
  {
    id: 1,
    name: "Pansy Rolling",
    email: "[email protected]",
  },
  {
    id: 2,
    name: "Klaus Hrycek",
    email: "[email protected]",
  },
  {
    id: 3,
    name: "Anabella Ellaway",
    email: "[email protected]",
  },
  {
    id: 4,
    name: "Leonard Pickless",
    email: "[email protected]",
  },
  {
    id: 5,
    name: "Loy Liddel",
    email: "[email protected]",
  },
];
  return (
   <UserContext.Provider value={data}>
    <div className="App">
      <Users/>
    </div>
   </UserContext.Provider>
  );
}
ReactDOM.render(
    <App />,
    document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Lastly I would summarize the idea in few steps.

  • First you have to create a context
  • Secondly you need to wrap you App level component under context provider
  • Pass the data to provider so that you can access in children components

So the overall idea is to create context first like below

import { createContext } from "react";
const UserContext = createContext();
export default UserContext;

Then wrap you App level component inside provider with data function App() {

const data = [
  {
    id: 1,
    name: "Pansy Rolling",
    email: "[email protected]",
  },
  {
    id: 2,
    name: "Klaus Hrycek",
    email: "[email protected]",
  },
  {
    id: 3,
    name: "Anabella Ellaway",
    email: "[email protected]",
  },
  {
    id: 4,
    name: "Leonard Pickless",
    email: "[email protected]",
  },
  {
    id: 5,
    name: "Loy Liddel",
    email: "[email protected]",
  },
];
  return (
    <UserContext.Provider value={data}>
       <Users/>
    </UserContext.Provider>
  );
}

export default App;

And then consume it in children component like below

import { useContext } from "react";
const Users = () => {
  const users = useContext(UserContext);
  //to access in JSX, you have to use Consumer
  return (
    <UserContext.Consumer>
      {(users) => (
        <div>
          {users.map((user, _) => (
            <div key={user.id}>
              <h4>{user.id}</h4>
              <h5> {user.name}</h5>
              <h6>{user.email}</h6>
            </div>
          ))}
        </div>
      )}
    </UserContext.Consumer>
  );
};

I hope it will solve your problem. Please accept this answer if it answer your question. Thanks Cheers :)

  • Related