Context Api React

Heeeeey guys!

My name is Gustavo Scarpim, and I will show you how to add Context Api simply and quickly to your project.

1º Create a folder called context inside your src folder, example:

2º Inside index we will create your global context, example…


This content originally appeared on DEV Community and was authored by Gustavo Scarpim

Heeeeey guys!

My name is Gustavo Scarpim, and I will show you how to add Context Api simply and quickly to your project.

1º Create a folder called context inside your src folder, example:

Alt Text

2º Inside index we will create your global context, example:

import React from "react"

import { ColorDefaultContextProvider } from "./template/components/colors"

const GlobalContext = ({ children }) => {
  return (
    <>
      <ColorDefaultContextProvider>{children}</ColorDefaultContextProvider>
    </>
  )
}

export default GlobalContext

3º I created a folder called components to separate my states, in my colors.js folder I create all my global states related to color, I'm taking the value of localStorage but the correct thing is to get the data from an API.
Well the example below is a "pattern of the context", just follow this step that is in the code below that will work

import React, { createContext, useState } from "react";

const colorCard = localStorage.getItem('colorCard')
const colorBackAvatar = localStorage.getItem('colorBackAvatar')
const colorTitle = localStorage.getItem('colorTitle')
const colorSubTitle = localStorage.getItem('colorSubTitle')

const DEFAULT_VALUE = {
  state: {
    colorCard: colorCard,
    colorBackAvatar: colorBackAvatar,
    colorTitle: colorTitle,
    colorSubTitle: colorSubTitle
  },
  setState: () => { },
};

const Context = createContext(DEFAULT_VALUE);

const ColorDefaultContextProvider = ({ children }) => {
  const [state, setState] = useState(DEFAULT_VALUE.state);
  return (
    <Context.Provider
      value={{
        state,
        setState,
      }}
    >
      {children}
    </Context.Provider>
  );
};

export { ColorDefaultContextProvider };
export default Context;

5º Finally, just import the context that we will use in your component, down here I show you how to call and edit its global state.

import React, { useContext, useRef } from 'react'
import * as S from './styles/custom'

import ContextColors from '../context/template/components/colors'

export default function Custom() {
  const { setState: setGlobalState } = useContext(ContextColors)
  const { state } = useContext(ContextColors);

  const colorCard = useRef(state.colorSubTitle)

  const handleChangeColorBackCard = (e) => {
    setTimeout(() => {
      //Here I’m taking all the state I have in my 
      // context and I’m changing a specific state, 
      // then save it in localStorage
      //(not required to save in localStorage)
      setGlobalState({ ...state, colorCard: e.target.value })
      localStorage.setItem('colorCard', state.colorCard)
    }, 300)
  }

  return (
    <S.Container>

      <S.ContentColor>
        <input ref={colorCard} defaultValue={state.colorCard}
          type={'color'} onChange={(e) => handleChangeColorBackCard(e)} />
        <S.Label>Background card</S.Label>
      </S.ContentColor>

    </S.Container>
  )
}

6º Most importantly, for the context to work throughout your application you need to import it into your main index

import React from 'react';
import ReactDOM from 'react-dom';
import Context from './context';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <Context>
      <App />
    </Context>
  </React.StrictMode>,
  document.getElementById('root')
);

And ready, you applied your context api to your project:

Alt Text

See the project working:

Project in action

See the complete code here on GitHub Click here

Check out the Project in action Deploy

Thanks for reading.


This content originally appeared on DEV Community and was authored by Gustavo Scarpim


Print Share Comment Cite Upload Translate Updates
APA

Gustavo Scarpim | Sciencx (2021-04-17T04:40:39+00:00) Context Api React. Retrieved from https://www.scien.cx/2021/04/17/context-api-react/

MLA
" » Context Api React." Gustavo Scarpim | Sciencx - Saturday April 17, 2021, https://www.scien.cx/2021/04/17/context-api-react/
HARVARD
Gustavo Scarpim | Sciencx Saturday April 17, 2021 » Context Api React., viewed ,<https://www.scien.cx/2021/04/17/context-api-react/>
VANCOUVER
Gustavo Scarpim | Sciencx - » Context Api React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/17/context-api-react/
CHICAGO
" » Context Api React." Gustavo Scarpim | Sciencx - Accessed . https://www.scien.cx/2021/04/17/context-api-react/
IEEE
" » Context Api React." Gustavo Scarpim | Sciencx [Online]. Available: https://www.scien.cx/2021/04/17/context-api-react/. [Accessed: ]
rf:citation
» Context Api React | Gustavo Scarpim | Sciencx | https://www.scien.cx/2021/04/17/context-api-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.