DEV Community

Cover image for Part4- Context Api in React Class Based Component
AKSH DESAI
AKSH DESAI

Posted on

Part4- Context Api in React Class Based Component

=> Here Folder Structure image here:

Folder Photo

Index.js Code:-_

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

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
)
Enter fullscreen mode Exit fullscreen mode

App.js Code:-

import React, { Component } from 'react'
import User from './User'
import { Provider } from './Context'

export default class App extends Component {
    state = {
        name: 'Rahul',
        value: 10
    };

    handleClickContext = () => {
        this.setState({
            value: this.state.value + 1
        });
    }

    render() {
        const contextValue = {
            data: this.state,
            handleClick: this.handleClickContext
        };
        return (
            <Provider value={contextValue}>
                <User />
            </Provider>
        )
    }
}


Enter fullscreen mode Exit fullscreen mode

User.js Code:

import React, { Component } from 'react'
import Guest from './Guest'

export default class User extends Component {
  render() {
    return (
      <div>
        <h3>User component</h3>
        <Guest />
      </div>
    )
  }
}

Enter fullscreen mode Exit fullscreen mode

Guest.js Code:

import React, { Component } from 'react'
import { myContext } from './Context';
// import { Consumer } from './Context'

export default class Guest extends Component {
    static contextType = myContext;

    componentDidMount() {
        console.log(this.context);
    }

    render() {
        console.log('a', this.context);
        const { name, value } = this.context.data;
        return (
            <div>
                <h3>Guest Component</h3>

                {/* <h4>Name: {this.context.data.name} Value: {this.context.data.value}</h4>
                <button onClick={this.context.handleClick}>Change Value</button> */}

                <h4>Name: {name} Value: {value}</h4>
                <button onClick={this.context.handleClick}>Change Value</button>

            </div>
        )
    }
}



Enter fullscreen mode Exit fullscreen mode

Context.js Code:

import React from 'react'
export const myContext = React.createContext();
console.log('a', myContext);
export const Provider = myContext.Provider;
// export const Consumer = myContext.Consumer;
Enter fullscreen mode Exit fullscreen mode

Output Photo

Output Photo

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)