sf-wdi-gaia/react(opens in a new tab)
Language: JavaScript
[react, js]
- stars
- 13
- watchers
- 5
- forks
- 84
- open issues
- 5
- Last updated
- 07/13/2016
Language: JavaScript
[react, js]
#ReactJS
This workshop is important because:
React is a library that Facebook invented to help build custom HTML elements. React provides a declarative library that keeps the DOM (the view) in sync with your data (the model). It is concerned only with the V in MVC and as a result can be used in conjunction with other libraries to help manage state.
After this workshop, developers will be able to:
Before this workshop, developers should already be able to:
##From Docs
We built React to solve one problem: building large applications with data that changes over time.
Many people choose to think of React as the V in MVC.
In fact, with React the only thing you do is build components. Since they're so encapsulated, components make code reuse, testing, and separation of concerns easy.
##JSX
JSX is a JavaScript syntax extension that looks similar to XML that helps represent DOM elements in JavaScript.
var myElement = <MyComponent someProperty={true}/>;
Here's an example of JSX, don't worry about understanding it just yet.
var Nav, Profile; // Input (JSX): var app = <Nav color="blue"><Profile>click</Profile></Nav>; // Output (JS): var app = React.createElement( Nav, {color:"blue"}, React.createElement(Profile, null, "click") );
###JSX Syntax in Sublime
To view JSX appropriately in Sublime:
babel in sublimeBabel > Javascript (Babel)###Getting Started
cd into starter-code
readme.md file at the root of the application to see how to get it setup.The basic unit you'll be working with in ReactJS is a component.
It is common to separate HTML, CSS and Javascript from one another.
In app/components/hello-world.jsx let's create a super simple component that just says, "Hello World". In order to do this we're going to write in ES6 as it makes the syntax easier (and yes, we are consciously not using semicolons).
class HelloWorld extends React.Component { render() { return <p>Hello World!</p> } }
From above, we can see that we are create a new Component class that is inheriting from React.Component. It has one function render. React expects render to be defined as that is the function that will get called when it is being rendered to the DOM. Note we are using ES6's method definition syntax.
Don't forget to require React and export your new component!
import React from 'react' class HelloWorld extends React.Component { render() { return <p>Hello World!</p> } } export default HelloWorld
It could be refactored to export the new class in the same line it is being defined.
import React from "react" export default class HelloWorld extends React.Component { render() { return <p>Hello World!</p> } }
###The Virtual DOM
var photo = new Image in the console; that photo is part of the virtual DOM.So we've created the template for our component. But how do we actually render it?
The below .render function takes two arguments:
ReactDOM.render( <HelloWorld/>, document.getElementById("hello-world-component") );
In your app/index.jsx let's import the new component and render it to the DOM. React is used for creating web components, while ReactDOM (used above) is used for actually rendering these elements to the DOM. Let's import our component and ReactDOM to get this working. It may look something like this:
"use strict" import React from 'react' import ReactDOM from 'react-dom' import HelloWorld from './components/hello-world' ReactDOM.render( <HelloWorld/>, document.getElementById("hello-world-component") )
Note: It's a good idea to use
"use strict"as it is a restricted variant of JavaScript that eliminates some of JavaScript's silent errors by changing them to throw errors.
Our Hello component isn't too helpful. Let's make it more interesting.
Hello component without hardcoding it into our render method?// update your HelloWorld Component to accept a name prop export default class HelloWorld extends React.Component { render() { return <p>Hello {this.props.name}!</p> } }
// render it by passing in a `name` prop ReactDOM.render( <HelloWorld name="WDI"/>, document.getElementById("hello-world-component") )
What are .props?
.props method..render method.We can create multiple properties for a component.
export default class HelloWorld extends React.Component { render() { return ( <div> <p>Hello {this.props.name}</p> <p>You are {this.props.mood}!</p> </div> ) } }
Note, if you have nested html elements in your JSX you have to wrap them in parenthesis.
ReactDOM.render( <HelloWorld name="WDI" mood="loving life"/>, document.getElementById("hello-world-component") )
Create a component called <Greeting/> that has two props: timeOfDay and object, such that it's interface would be <Greeting timeOfDay="night" object="moon"> and it would print out "Goodnight moon" in an h3. Append it to a div with the id greeting-component.
class Greeting extends React.Component { render() { return( <h3>Good{this.props.timeOfDay} {this.props.object}</h3> ) } }
ReactDOM.render( <Greeting timeOfDay="night" object="moon"/>, document.getElementById("greeting-component") )
###Variable Props
What if we don't know exactly what props we're going to get but we want to pass them to the element. We can do this with something new in ES6 called a spread operator.
For example lets say we to create ProfilePic component that is a clickable image tag and we want to be able to pass in any new props into it.
class ProfilePic extends React.Component { render() { return ( <a {...this.props}> <img style={{width: '200px'}} src="http://bit.ly/1MItzOs"/> </a> ) } }
Where we see {...this.props} is where all props we pass in will live. So now we can set an href and class on our element by just passing them in!
Note because
classis a reserved word in ES6 we have to useclassNameinstead.
ReactDOM.render( <ProfilePic href="http://www.nyan.cat/" className="profile-pic"/>, document.getElementById("profile-pic-component") )
###Nested Components
What if we want to add text just above our Image, but want it also to be wrapped in the anchor tag so it is clickable, like the image?
Well could we just put in some text inside of our ProfilePic component like such? You can nest HTML after all!
ReactDOM.render( <ProfilePic href="http://www.nyan.cat/" className="profile-cat"> <h3>This Kitten Cashes Checks</h3> </ProfilePic>, document.getElementById("profile-pic-component") )
Yes, we could do this! We would just need to modify our original component to render any children we pass in the correct place, which is done with this.props.children.
class ProfilePic extends React.Component { render() { return ( <a {...this.props}> {this.props.children} <img style={{width: '200px'}} src="http://bit.ly/1MItzOs"/> </a> ) } }
###Challenge: Mr Cat's Profile
id into the ProfilePic component that is "mr-cat"p child, below the h3, into the ProfilePic component with the class "bio" that contains a brief description of this kitty.##Exercise: A Blog Post
Let's practice what we've learned so far by building a Post component for our blog.
Make and render a custom <Post/> component with the attributes title, author, and body. The exact HTML/CSS composition of the component is up to you.
class Post extends React.Component { render() { return ( <div class="post"> <h2>Hello {this.props.title}</h2> <h4>By {this.props.author}</h4> <p>{this.props.body}</p> </div> ) } }
ReactDOM.render( <Post title={"Are you feline me?"} author={"Kitkat the Cat"} body={"Cause I'm purrfect"} />, document.getElementById("blog-component") )
What if we wanted to add an array of comments to the post?
ReactDOM.render( <Post title={"Are you feline me?"} author={"Kitkat the Cat"} body={"Cause I'm purrfect"} comments={["first!", "more gifs plz", "i haz had enuf ov dis >_<"]} />, document.getElementById("blog-component") )
class Post extends React.Component { render() { return ( <div className="post"> <h2>{this.props.title}</h2> <h4>By {this.props.author}</h4> <p>{this.props.body}</p> <h3>Comments</h3> <ul> { this.props.comments.map((comment, index) => { return <li key={index}>{comment}</li> }) }</ul> </div> ) } }
Note: when iterating through a collection, React needs to put a
keyon each item with a unique index for that collection (otherwise an errors will appear)..map's second argument to it's callback is the (unique) index, so that works just fine. However, the actual unique database id on each comment would be better.
ReactDOM.render( <Post title={myPost.title} author={myPost.author} body={myPost.body} comments={myPost.comments} />, document.getElementById("blog-component") )
What if there was a comment component we could abstract some of this logic to?
Let's reference a comment using an embedded <Comment/> component inside of PostView's render method.
Comment component in the same way we did for Post.Comment render method should render a body property.Post's render method so that its return value generates as many <Comment/> elements as there are comments.class Post extends React.Component { render() { return ( <div className="post"> <h2>{this.props.title}</h2> <h4>By {this.props.author}</h4> <p>{this.props.body}</p> <h3>Comments</h3> <ul> { this.props.comments.map((comment) => { return <Comment key={index} body={comment}/> }) }</ul> </div> ) } } class Comment extends React.Component { render() { return ( <li>{this.props.body}</li> ) } }
We already went over properties.
this.state.val.Let's modify our earlier HelloWorld example to be a new MoodTracker component. There will be a mood displayed and eventually a user will click a button to indicate on a scale of 1-10 how much of that mood they are feeling.
Now, let's instead use React's .createClass method as opposed to extending standard ES6 classes, as it makes some of this behavior more straightforward.
const MoodTracker = React.createClass({ getInitialState() { return {points: 1} }, render() { return ( <div> <p>Hello {this.props.name}</p> <p>On a scale of 1-10</p> <p>You are {this.props.mood}</p> <p>This much: {this.state.points}</p> </div> ) } })
Next we need to enable the user to change the state of our component. Let's create an onClick event that triggers a method increaseMood to increment our counter by 1 for each click. Notice that it is important to use the .setState method to update the state. Also, we can define the initial state with getInitialState a reserved method in React.
const MoodTracker = React.createClass({ getInitialState() { return {points: 1} }, increaseMood() { this.setState({ points: this.state.points + 1 }) }, render() { return ( <div> <p>Hello {this.props.name}</p> <p>On a scale of 1-10</p> <p>You are {this.props.mood}</p> <p>This much: {this.state.points}</p> <button onClick={this.increaseMood}>Up Your Mood!</button> </div> ) } })
Whenever we run .setState, our component runs a diff between the current DOM and the virtual DOM node to update the state of the DOM in as few manipulations as possible.
After 10 clicks, the user should see the counter reset to 1.
Example solutionconst MoodTracker = React.createClass({ getInitialState() { return {points: 1} }, increaseMood() { let newPoints = this.state.points >= 10 ? 1 : this.state.points + 1 this.setState({ points: newPoints }) }, render() { return ( <div> <p>Hello {this.props.name}</p> <p>On a scale of 1-10</p> <p>You are {this.props.mood}</p> <p>This much: {this.state.points}</p> <button onClick={this.increaseMood}>Up Your Mood!</button> </div> ) } })
Let's create a state for our earlier blog example. We want to be able to edit the body of our post. Tip: update the component to the React.createClass syntax.
likes state for our Post component that defaults to 0.like that adds 1 to the state's number of likes.Checkout the solution-code directory.