=> Here Folder Structure image here:
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>
)
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>
)
}
}
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>
)
}
}
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>
)
}
}
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;
Output Photo
Top comments (0)