I am trying to get my head around ReactJs context, and have finally made some progress to display the state name and countNumber.
However I am still struggling to work out how to replace the current state, which is used in my formatCount() function.
Can anyone let me know how you would do this in my example below?
I would like to use the number in my context e.g. 5 in the method, formatCount(), so it would be something like
formatCount() {
const currentCount = {c.state.currentCount};
return currentCount === 0 ? "Zero" : currentCount;
}
Here is my context
import React, { Component } from "react";
export const CounterContext = React.createContext();
export default class CounterProvider extends Component {
state = {
state: { name: 'bob', currentCount: 5 },
}
render() {
return (
<CounterContext.Provider value={ this.state }>
{this.props.children}
</CounterContext.Provider>
)
}
}
Here is my counter component
import React, { Component } from "react";
import { RouteComponentProps } from "react-router";
import { CounterContext } from "../contexts/context.js";
export class Counter extends Component {
state = { currentCount: 7 }
render() {
return <div className="m-2">
<CounterContext.Consumer>
{c =>
<div className="m-2">
<p>My name is {c.state.name} - {c.state.currentCount}</p>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button className="btn btn btn-primary btn-sm m-2" onClick={() => { this.incrementCounter() }}>Increment</button>
<button className="btn btn-danger btn-sm m-2" onClick={() => { this.incrementCounter() }}>Delete</button>
</div>
}
</CounterContext.Consumer>
</div>;
}
formatCount() {
const currentCount = this.state.currentCount;
return currentCount === 0 ? "Zero" : currentCount;
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.currentCount === 0 ? "warning" : "primary";
return classes;
}
incrementCounter() {
this.setState({
currentCount: this.state.currentCount + 1
});
}
}