Commit e021dc8e authored by Kristian Freeman's avatar Kristian Freeman

Answer key - interacting React state

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