Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

setup context api

//# Contect.js 
import { useEffect, useState, createContext } from "react";

export const CharityContext = createContext();

export const CharityContextProvider = ({ children }) => {
  const loki = "chaulagain";
  return <CharityContext.Provider value={{ loki }}>{children}</CharityContext.Provider>;
};

//# app.js
import { CharityContextProvider } from "../context/Context";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <CharityContextProvider>
      <Component {...pageProps} />
    </CharityContextProvider>
  );
}

export default MyApp;

//# fetch data in any file
import React, { useContext } from "react";
import { CharityContext } from "../context/Context";

function Index() {
  const { loki } = useContext(CharityContext);
  console.log(loki); //-->Result:Chaulagain
  return <div>Index</div>;
}

export default Index;


Comment

context api react

import React from "react";
// 1. Create context - storing values
export const CartContext = React.createContext();
// CartContext.Provider
// this is you create that context box
// Provider

export function CartContextProvider({ children }) {
  const [cartCount, setCartCount] = React.useState(0);
  const handleCartUpdate = (val) => {
    setCartCount(cartCount + val);
  };
  const handleDec=(val)=>{

    setCartCount(cartCount + val);
  }

  return (
    <CartContext.Provider value={{ cartCount, handleCartUpdate,handleDec }}>
      {children}
    </CartContext.Provider>
  );
}

=====================navbar.jsx
import React from "react";
import { CartContext } from "../Context/CardContexr";

const Navbar = () => {
  const { cartCount } = React.useContext(CartContext);
  const{handleCartUpdate}= React.useContext(CartContext)
//   const { theme } = React.useContext(ThemeContext);

  return <>
  
  <h1 >Cart Count : {cartCount}</h1>

  <button onClick={()=>{handleCartUpdate(1)}} >change</button>
  </>
};

export default Navbar;



Comment

react context api

DEFINITION::::::
Context provide a way to pass data through the component tree without 
having to pass down manually at every level

HOW TO USE::::::
DECLARATION:::
	const MyContext = React.createContext()
Creating a new Context for each unique piece of data that needs to be available
throughout your component data
	const LocaleContext = React.createContext()
Properties of LocaleContext --------
	LocaleContext.Provider
    LocaleContext.Consumer

What is a Provider 
	Allows us to "declare the data that we want available throughout our
	component tree"

What is a Consumer
	Allows "any component in the tree that needs that data to be able to 
    subscibe to it"

How to use Provider	
	<MyContext.Provider value={data}>
      <App />
    </MyContext.Provider>




Comment

React Context API

import React, { useState } from 'react'

const GlobalStateContext = React.createContext({ })

export const GlobalStateProvider = ({ children }) => {
    const [config, setConfig] = useState({
        projectInfo: ''
    })
    const [projectFile, setProjectFile] = useState('./test.cpp')
    const [executionState, setExecutionState] = useState("NoProject")

    return (
        <GlobalStateContext.Provider
            value={{
                executionState,
                config,
                projectFile,
                setExecutionState,
                setConfig,
                setProjectFile,
            }}
        >
            {children}
        </GlobalStateContext.Provider>
    )
}

export default GlobalStateContext
Comment

react context api

import { createContext, useContext, useReducer } from "react";

const Actions = {
	SET_ITEMS: "SET_ITEMS",
};

const reducer = (state, action) => {
	if (action.type === Actions.SET_ITEMS) {
		return { ...state, items: action.payload };
    }

	return state;
};

const initialState = {
	items: []
};

const SimpleContext = createContext(initialState);
export const useSimpleContext = () => useContext(SimpleContext);
export const SimpleProvider = ({ children }) => {
	const [state, dispatch] = useReducer(reducer, initialState);

	function setItems(items) {
		dispatch({ type: Actions.SET_ITEMS, payload: items });
	}

	return <SimpleContext.Provider value={{ state, setItems }}>{children}</SimpleContext.Provider>;
};
Comment

Context Api in react

// In App.js 
<NoteState>
	components where you want to use this context which you created    
</NoteState>

// In NoteContext.js 
import { createContext } from "react";

const NoteContext = createContext();

export default NoteContext;

// In NoteState.js or whatever name you want to give
import NoteContext from "./NoteContext";

const NoteState = (props)=>{
  // you can also pass state here also or functions also 
    const user = {
        name: "Gourav Khurana",
        age: 19,
        caast: "General"
    }
    return (
        <NoteContext.Provider value={user}>
            {props.children}
        </NoteContext.Provider>
    )
}
export default NoteState;


This is all about Context API how to create it and add it to Components 

Now how to use it in the Components :- 
  
import React, { useContext } from 'react';
import NoteContext from "../contexts/notes/NoteContext";

const About = () => {
    const contextValue = useContext(NoteContext);
    return (
       you can simply use here. 
    )
}

export default About
Comment

Context Api in react

// In App.js 
<NoteState>
	components where you want to use this context which you created    
</NoteState>

// In NoteContext.js 
import { createContext } from "react";

const NoteContext = createContext();

export default NoteContext;

// In NoteState.js or whatever name you want to give
import NoteContext from "./NoteContext";

const NoteState = (props)=>{
  // you can also pass state here also or functions also 
    const user = {
        name: "Gourav Khurana",
        age: 19,
        caast: "General"
    }
    return (
        <NoteContext.Provider value={user}>
            {props.children}
        </NoteContext.Provider>
    )
}
export default NoteState;


This is all about Context API how to create it and add it to Components 

Now how to use it in the Components :- 
  
import React, { useContext } from 'react';
import NoteContext from "../contexts/notes/NoteContext";

const About = () => {
    const contextValue = useContext(NoteContext);
    return (
       you can simply use here. 
    )
}

export default About
Comment

context api example in react

class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  // The Toolbar component must take an extra "theme" prop
  // and pass it to the ThemedButton. This can become painful
  // if every single button in the app needs to know the theme
  // because it would have to be passed through all components.
  return (
    <div>
      <ThemedButton theme={props.theme} />
    </div>
  );
}

class ThemedButton extends React.Component {
  render() {
    return <Button theme={this.props.theme} />;
  }
}
Comment

Context Api in react

// In App.js 
<NoteState>
	components where you want to use this context which you created    
</NoteState>

// In NoteContext.js 
import { createContext } from "react";

const NoteContext = createContext();

export default NoteContext;

// In NoteState.js or whatever name you want to give
import NoteContext from "./NoteContext";

const NoteState = (props)=>{
  // you can also pass state here also or functions also 
    const user = {
        name: "Gourav Khurana",
        age: 19,
        caast: "General"
    }
    return (
        <NoteContext.Provider value={user}>
            {props.children}
        </NoteContext.Provider>
    )
}
export default NoteState;


This is all about Context API how to create it and add it to Components 

Now how to use it in the Components :- 
  
import React, { useContext } from 'react';
import NoteContext from "../contexts/notes/NoteContext";

const About = () => {
    const contextValue = useContext(NoteContext);
    return (
       you can simply use here. 
    )
}

export default About
Comment

PREVIOUS NEXT
Code Example
Javascript :: check last url in javascript 
Javascript :: javascript object get value by key 
Javascript :: electron ipc from main to renderer 
Javascript :: node js clear cache 
Javascript :: javascript initialize two array in one line 
Javascript :: what regular expression will match valid international phone numbers 
Javascript :: use of split and join 
Javascript :: UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON 
Javascript :: javascript string() function 
Javascript :: javascript delete user input value in array 
Javascript :: counting sheep 
Javascript :: node red debug to console 
Javascript :: js is variable int 
Javascript :: apollo client nextjs 
Javascript :: javascript number if .00 truncate 
Javascript :: react merge two objects 
Javascript :: sequelize transaction config 
Javascript :: change the color of toast toastr js 
Javascript :: Error: ENOENT: no such file or directory, lstat ode_modules@react-navigationcoresrcgetStateFromPath.tsx 
Javascript :: react typescript set type 
Javascript :: save previousdata react 
Javascript :: How to iterate elements in an object 
Javascript :: react chartjs 2 
Javascript :: index localstorage object 
Javascript :: input set variable angular 
Javascript :: format iso time in human readable format with moment js 
Javascript :: range number in js 
Javascript :: axios error network error 
Javascript :: find intersection between two object arrays javascript 
Javascript :: create a promise in javascript 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =