Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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;



 
PREVIOUS NEXT
Tagged: #context #api #react
ADD COMMENT
Topic
Name
5+4 =