# Manipulating/Changing Context

## Manipulating Context by Changing State

We can manipulate component's `context` by changing their `state.`

{% tabs %}
{% tab title="Header.js" %}

```jsx
import React, {Component} from "react"
import {ThemeContextConsumer} from "./themeContext"

function Header(props) {
    return (
        // Consuming Context
        <ThemeContextConsumer>
            {context => (
                <header className={`${context.theme}-theme`}>
                    <h2>{context.theme === "light" ? "Light" : "Dark"} Theme</h2>
                </header>
            )}
        </ThemeContextConsumer>
    )    
}

export default Header

```

{% endtab %}

{% tab title="Button.js" %}

```jsx
import React from "react"
import {ThemeContextConsumer} from "./themeContext"

function Button(props) {
    return (
        // Consuming Context
        <ThemeContextConsumer>
            {context => (
                <button onClick={context.toggleTheme} className={`${context.theme}-theme`}>Switch Theme</button>
            )}
        </ThemeContextConsumer>
    )    
}

export default Button

```

{% endtab %}

{% tab title="App.js" %}

```jsx
import React from "react"

import Header from "./Header"
import Button from "./Button"

function App() {
    // Context Consumer Components
    return (
        <div>
            <Header />
            <Button />
        </div>
    )
}

export default App
```

{% endtab %}

{% tab title="themeContext.js" %}

```jsx
/**
 * Challenge:
 * 1) Add state to hold the current theme
 * 2) Add a method for flipping the state between light and dark
 * 
 */

import React, {Component} from "react"

// Destructing the Provider & Consumer property from Context
const {Provider, Consumer} = React.createContext()

// Craeting a Context Provider
class ThemeContextProvider extends Component {
    // Initialing state
    state = {
        theme : "light"
    }
    
    // Class method
    toggleTheme = () => {
        this.setState(prevState => {
            return {
               theme: prevState.theme === "light" ? "dark" : "light" 
            }
        })
    } 
    
    render() {
        return (
            // Passing objects to Consumer
            <Provider value={{theme: this.state.theme, toggleTheme: this.toggleTheme}}>
                {this.props.children}
            </Provider>
        )
    }
}

// Exporting Provider & Consumer
export {ThemeContextProvider, Consumer as ThemeContextConsumer}

```

{% endtab %}

{% tab title="index.js" %}

```jsx
import React from "react"
import ReactDOM from "react-dom"

import App from "./App"
import {ThemeContextProvider} from "./themeContext"

ReactDOM.render(
    // Rendering our ThemeContextProvider Class component into DOM tree
    <ThemeContextProvider>
        <App />
    </ThemeContextProvider>, 
    document.getElementById("root")
)

```

{% endtab %}
{% endtabs %}
