DEV Community

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

Posted on

Part3- Context Api in React Class Based Component

=> Here Folder Structure image here:

Folder Output

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'

export default class App extends Component {
    render() {
        return (
            <User />
        )
    }
}

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 { Consumer1 } from './Context'

export default class Guest extends Component {
    render() {
        return (
            <div>
                <h3>Guest Component</h3>
                <Consumer1>
                    {(value) =>
                        <>
                            {value}
                        </>
                    }
                </Consumer1>
            </div>
        )
    }
}


Enter fullscreen mode Exit fullscreen mode

Context.js Code:

import React from 'react'
const myContext1 = React.createContext('aksh');
export const Provider1 = myContext1.Provider;
export const Consumer1 = myContext1.Consumer; 
Enter fullscreen mode Exit fullscreen mode

Output Photo
Output Photo

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)