Last active
July 10, 2020 03:05
-
-
Save nimahkh/9c008aaf2fd2d1cc83cd98c61e54979a to your computer and use it in GitHub Desktop.
reactjs simple context functions to manage states
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.App { | |
text-align: center; | |
} | |
.App-logo { | |
animation: App-logo-spin infinite 20s linear; | |
height: 40vmin; | |
pointer-events: none; | |
} | |
.App-header { | |
background-color: #282c34; | |
min-height: 100vh; | |
display: flex; | |
flex-direction: column; | |
align-items: center; | |
justify-content: center; | |
font-size: calc(10px + 2vmin); | |
color: white; | |
} | |
.App-link { | |
color: #61dafb; | |
} | |
@keyframes App-logo-spin { | |
from { | |
transform: rotate(0deg); | |
} | |
to { | |
transform: rotate(360deg); | |
} | |
} | |
.fullWidth{ | |
width:100%; | |
height:500px | |
} | |
.blue{ | |
background-color: #61dafb; | |
} | |
.green{ | |
background-color: darkgreen; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import {StateProvider} from "./state" | |
import './App.css'; | |
import {Button} from "./Button"; | |
const App = () => { | |
const initialState = { | |
theme: {primary: 'green'} | |
}; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'changeTheme': | |
return { | |
...state, | |
theme: action.newTheme | |
}; | |
default: | |
return state; | |
} | |
}; | |
return ( | |
<StateProvider initialState={initialState} reducer={reducer}> | |
<Button/> | |
</StateProvider> | |
); | |
} | |
export default App; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {createContext, useContext, useReducer} from 'react'; | |
export const StateContext = createContext(); | |
export const StateProvider = ({reducer, initialState, children}) => { | |
const [state, dispatch]= useReducer(); | |
return( | |
<StateContext.Provider value={}> | |
{children} | |
</StateContext.Provider> | |
) | |
}; | |
export const useStateValue = () => useContext(StateContext); | |
export const useStateDisptach = () => useContext(StateDispatchContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment