Hey there, Today we are starting fresh! No longer satisfied by merely saying “hello”, we are launching into exciting new uncharted waters: turning the lights on and off! ? I know, it’s very exciting. I'm excited, anyway. Over the last couple days you’ve…
In today’s lesson we’re going to break away from static pages by learning how to use state. Our project will be a page where the user can toggle the lights on and off by clicking a button. And by “the lights” I mean the background color (but hey, if you hook this up to an IoT thing in your house, I totally want to hear about it!). Create the ProjectWe’re gonna start with a brand new project. Go here: https://codesandbox.io/s/new, erase the contents of index.js, and type this in: This is nothing you haven’t seen before. Just a Make the component statefulI don’t know if you know this about light switches, but they can be in one of two states: ON and OFF. Conveniently React has a feature called state which allows components to keep track of values that can change – a perfect place to store the state of our light. In order to add state to our Now that Render according to stateRight now, the component works the same as before, because we haven’t changed anything in As you can see, the light is still on. Now change Ok so this isn’t very exciting yet; we’ve proved that we can change the display by changing the code ? But we’re getting there. Change the state when you click the buttonLet’s add a button and kick this thing into high gear. Change the div to look like this: So we’ve got a plain old line break with the Above the render() function, and under the state initialization, add this code: Remember how we talked about arrow functions yesterday? This is one of those. Except it’s inside a class, which makes it a member function. Click the “flip” button now. Does it work? Hooray! We’ll fix the stark white background in a sec, but let’s talk about this How setState worksIn the flipLight function, we’re toggling the isLit state true/false depending on what it’s currently set to. You might wonder why we don’t just say
If you just change We’re alllmost done here, but I promised that the background color would change, and it did not. Yet. Change the background colorTo do that we’re going to use some CSS. Plain old CSS. In the CodeSandbox editor, hover over the “src” folder on the left and click the “New File” button. Name it At the top, we are setting the height of absolutely-freaking-everything to 100%, so that the whole page goes dark instead of just the top 20 pixels. Then we have “lit” and “dark”, which will change the background and text color accordingly. Now click over to index.js, and at the top of the file, import the CSS file like so: Now all that’s left is to apply the “lit” and “dark” classes to the Room component. Remember how the <div> in Room has the prop At the top of render (above the return), add a variable for the brightness: Then use that variable, plus ES6’s template strings, to change the className on the div. Like this: The backticks signify a template string in ES6. Template strings allow you to insert variables within them, which is what the And finally the whole thing is surrounded by single braces because it’s an expression, and because React says so. I’m not sure why React allows you to just pass Click the button now, and you’ll see that the background color changes along with the text. Woohoo! ? If your code isn’t working, you can compare it to the final working example here. Your TurnRun through these quick exercises to solidify your understanding:
Look forward to tomorrow, where we get to fetch REAL data with an API and display it :) Talk to you then, P.S. State is one of the trickier concepts to grok in React. I put together a Visual Guide to State in React if the concept still seems a bit fuzzy. My Pure React book dedicates a couple chapters to handling state, including a shopping cart that we build step-by-step. |
To make sure you keep getting these emails, please add dave@daveceddia.com to your address book or whitelist us. Want out of the loop? Unsubscribe. My postal address: P.O. Box 248, Nutting Lake, MA |
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
class Room extends React.Component {
state = {
isLit: false,
isOn: false,
temperature:22
};
flipLight = () => {
this.setState({
isLit: !this.state.isLit
});
};
onLight = () => {
this.setState({
isOn: !this.state.isOn
});
};
addTem =()=>{
this.setState({
temperature: this.state.temperature + 1
});
}
render() {
const brightness = this.state.isLit ? "lit" :"dark";
return (
<div className={`room ${brightness}`}>
the room is {this.state.isLit ? "lit" : "dark"}
<br />
<button onClick={this.flipLight}>flip</button>
<br />
the Light is {this.state.isOn ? "on" : "off"}
<br />
<button onClick={this.onLight}>isOn</button>
<br />
the Temperature is {this.state.temperature}
<br />
<button onClick={this.addTem}>+</button>
</div>
);
}
}
ReactDOM.render(<Room />, document.getElementById("root"));
我的代码 :)