Load data into another component in ContextAPI

The Context API solves one major problem–prop drilling.ContextAPI or Redux can be used for PropDrilling problem. Load data into another component in ContextAPI.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

And sometimes, some components would have to receive the props only to pass it down to its children. This is known as Prop Drilling. 

In Below Image, you can see I have created one Button and table. On Button click the table loads with API Data. But Button is Components A and Table is in Components B . So Here we do use ContextAPI or Redux not Prop Drilling.

CRUD Operation in ContextAPI

Now you can see our Output image and Now below is the folder structure

Folder Structure of the Project

ContextAPI Folder Structure




First, make a context.js file that will be used for context support. Without this file, we cant use the context API concept in our project

src/context.js

import { createContext } from 'react';
export const AppContext = createContext();

Now I have created Header.js for menu

src/Header.js

import React from 'react'

function Header() {
    return (
        <div>
            <nav class="navbar navbar-dark bg-primary">
            <a class="navbar-brand" href="#" style={{color:"white"}}>Navbar</a>
           
            </nav>
        </div>
    )
}

export default Header

Now We will See each component by code. So first we will see sidebar ( Load Button Component)

src/componentsA/AddUser.js

import React, { useContext, useState } from 'react';
import { AppContext } from '../context';

const AddUser = () => {
	const { dispatchUserEvent } = useContext(AppContext);
	
    const [showdata ,setShowData] = useState([])

	const handleAddUser = (e) => {
        e.preventDefault();
       fetch('https://jsonplaceholder.typicode.com/users')
        .then(response => response.json())
        .then(data => setShowData(data))
		
		dispatchUserEvent('ADD_USER', { newUser: {showdata} });
	};

	return (
		<div  style={{background:"#f2f2f2",height:"500px",marginTop:"-20px"}}>
            <br/>
			<h3 className='text-success' style={{marginTop:"30px",position:"relative",textAlign:"center"}}>Load data</h3>
			
			<button className='btn btn-primary' onClick={handleAddUser}>Load User</button>

			<h6 className='text-success' style={{marginTop:"30px",position:"relative",textAlign:"center"}}>This Button is in Component  A</h6>
		
		</div>
	);
};

export default AddUser;

Now we will see table Component ( Left Content table )

src/componentsA/UserList.js

import React, { useContext } from 'react';
import { AppContext } from '../context';


const UserList = () => {
	const  {users} = useContext(AppContext);
    
	return (
		<div style={{background:"#ececec",height:"500px",marginTop:"-20px"}}>
            <br/>
			<h3 className='text-success' style={{marginTop:"30px",position:"relative",textAlign:"center"}}>Get Data from Another components in React JS</h3>
		    <h6 className='text-danger' style={{marginTop:"03px",position:"relative",textAlign:"center"}}>This Table is in Component Folder B</h6>
		
            <div style={{padding:"20px"}}>
			 {users.map((user) =>
                    <div>   
                      <table class="table">
                        <thead>
                        
                        </thead>
                        <tbody>
                        {user.showdata.map((name)=>
                        <tr>
                            <th>{name.id}</th>
                            <td>{name.name}</td>
                            <td>{name.username}</td>
                            <td>{name.website}</td>
                        </tr>)}
                        </tbody>
                    </table>
                   </div>
                    )} 
			</div>
		</div>
	);
};

export default UserList;

Now I will call both Components ( Button and Table Component ) in the LoadData.js file

import React, { useState } from 'react';
import './App.css';
import AddUser from './componentsA/AddUser';
import UserList from './componentsB/UserList';
import { AppContext } from './context';
import  Header from './Header';

function LoadData() {
	const [ users, setUsers ] = useState([]);
	
	const dispatchUserEvent = (actionType, payload) => {
		switch (actionType) {
			case 'ADD_USER':
				setUsers([payload.newUser]);
				return;

			default:
				return;
		}
	};

	return (
		<div className="App">
            <Header/>
            <div className='container-fluid'>
                <div className='row'>
                    <AppContext.Provider value={{ users, dispatchUserEvent }}>
                       <div className='col-md-3'>
                        <AddUser />
                       </div>
                       <div className='col-md-9'>
                          <UserList />
                       </div> 
                    </AppContext.Provider>
                </div>
           </div>
		</div>
	);
}

export default LoadData;

Just call the LoadData.js file in the main file ( App.js )

src/App.js

import './App.css';
import LoadData from './LoadData';


function App() {
  return (
    <div className="App">
        <LoadData/>
    </div>
  );
}

export default App;

Now run the code using npm start. So It will run on http://localhost:3000/

Subscribe my Youtube Channel Before Downloading the code

https://www.youtube.com/channel/UCKDxVGCfrvAx7OcO31bsXDA

Source Code : Download the Source Code

See our More Project in Laravel and ReactJS

Theme Color change in React JS

Records display in Material UI Table

Display Records in Model Box in React

Responsive Navbar in Material UI React

Upload PDF file in React, Laravel

Comments 3

Leave a Reply

Your email address will not be published. Required fields are marked *