Commit e021dc8e authored by Kristian Freeman's avatar Kristian Freeman

Answer key - interacting React state

parent 68bdad56
import React from 'react';
import ReactDOM from 'react-dom';
import React from "react";
import ReactDOM from "react-dom";
import registerServiceWorker from './registerServiceWorker';
import registerServiceWorker from "./registerServiceWorker";
export default class MyEnhancedButton extends React.Component {
constructor() {
super()
super();
// Initialize the state of this component:
// - count should be set to 0
// - oddNumber should be set to false
this.state = {
count: 0,
oddNumber: false
};
// this.onClick needs to be explicitly bound
// to the context `this` in the constructor.
// Re-assign this.onClick to a bound version
// of this.onClick, bound to the context `this`.
this.onClick = this.onClick.bind(this);
}
// Define the function onClick, which updates
// the state with count + 1.
//
// Also update oddNumber in state, depending on
// whether the new number will be an even or odd
// number.
//
// You may prefer to get count out of state as
// a separate value, and update the number with
// <myCurrentCountVariable> + 1.
onClick() {
const newCount = this.state.count + 1;
this.setState({
count: newCount,
oddNumber: newCount % 2 === 1
});
}
render() {
// Assign the value of count in state to the variable
// count.
const { oddNumber } = this.state;
// Set clickFunc to the onClick function for this component
const clickFunc = null;
const { count, oddNumber } = this.state;
const clickFunc = this.onClick;
const oddNumberString = oddNumber ? "True" : "False";
// Set oddNumberString to "True" if oddNumber is true,
// or "False" if oddNumber is false.
const oddNumberString = "";
return (
<div>
<p>The button has been clicked {count} times</p>
<p>Odd number? {oddNumberString}</p>
<button onClick={clickFunc}>
Click me
</button>
<button onClick={clickFunc}>Click me</button>
</div>
)
);
}
}
const root = document.getElementById('root');
if (root) { ReactDOM.render(<MyEnhancedButton />, root); }
const root = document.getElementById("root");
if (root) {
ReactDOM.render(<MyEnhancedButton />, root);
}
registerServiceWorker();
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment