< Back to Coding, React

Using Context in React

Using context allows access of certain data within all components inside the “provider” without having to pass them as props to the children. First create the context:

import React from 'react';
const MyContext = React.createContext();
export default MyContext;

Then make the provider:

import MyContext from "./myContext";
import React from 'react';

class MyProvider extends React.Component {
    state = {
        color: "red"
    }

    render() {

        return (
            <MyContext.Provider value={{

                color: this.state.color,
                toggleColor: () => {
                    let newColor = "";
                    if (this.state.color === "red") {
                        newColor = "green";
                    } else {
                        newColor = "red";
                    }

                    this.setState({ color: newColor });

                }

            }}>
                {this.props.children}
            </MyContext.Provider>

        )

    }

}

export default MyProvider;

Here, we import the context, and set up the data we want to share in the state and also a function that toggles the state. Then you wrap the provider around everything to make it ‘global’. To access the context in your components, you import the context and also wrap the component around a context consumer:

import React from 'react';
import MyContext from '../context/myContext';

const ContextComponent = () => (
    <>
        <MyContext.Consumer>

            {context => (<div>

                <p style={{color:context.color}}>
                child component - {context.color}
                </p>

                <button onClick={context.toggleColor}>toggle color</button>

            </div>)}

        </MyContext.Consumer>

    </>
)

export default ContextComponent;

So now this component has access to the context’s “color” and “toggleColor” function without having props passed to it.

You can also use context like this without having to wrap it around a Consumer:

function Something(){
    const {color} = React.useContext(MyContext);
    return <div>{color}</div>
}

Leave a Reply

Your email address will not be published.