3 Minute React Test Drive: Hello World the easy way(三分钟上手react--HelloWorld )

Dave Ceddia logo

Dave Ceddia

3 Minute React Test Drive: Hello World the easy way

APRIL 18, 2016

3 Minute React Test Drive

Trying to wrap your head around React, but haven’t written any code yet?

Maybe you’ve read some blogs, watched some videos, tried to understand how all the pieces fit together… You want to understand everything before you start building. And there are so many moving parts! React, Flux/Redux, Router, and on and on.

And at the same time, the basic React stuff almost seems too simple.

“React looks so simple on the surface… components are basically just functions that return the view based on the current state. Is this really manageable at scale?”

So let’s cut to the chase: it’s really hard to evaluate a library without writing any code, so we’re going to solve that right now :)

In this post, I’m going to show you how to write Hello World in 3 minutes, and then you can play around and go from there.

We’re going to do this in pure React – which means you don’t need to worry about Redux, routing, or even setting up a build or cloning a boilerplate project!

Step 0

Make sure you have Node.js and npm installed. If not, get it here. I’m assuming you’ve got this already. Does not count against the 3 minutes.

Step 1

Install react-heatpack. Open a terminal/command prompt and run:

npm install -g react-heatpack

React Heatpack is an awesome tool that will let you magically skip all of the build bullshit and get right down to writing an app. This is also the slowest step.

Step 2

Make a new directory. Call it anything you want. react-hello is a nice name.

Step 3

Create a file in that directory, name it index.js, and type this code in:

Type it out by hand? Like a savage?
Typing it drills it into your brain much better than simply copying and pasting it. You're forming new neuron pathways. Those pathways are going to understand React one day. Help 'em out.

import React from 'react'

export default React.createClass({
  render: function() {
    return <div>Hello React!</div>
  }
})

There’s a little ES6 going on here: import and export default… if that looks foreign, just ignore it for now (React can be written quite well in ES5 or ES6).

Step 4

From inside that directory, run the dev server and pass it the name of your index.js file:

heatpack index.js

Step 5

Open a browser to http://localhost:3000 (I even gave you a link!)

Step 6

There is no step 6. The app is working! You wrote a React app! Isn’t it tiny?

What now?

Now that we’ve got a scaffold in place, follow along with the exercises below and learn a little more!

Under the Hood: What is react-heatpack doing?

react-heatpack sets up a Webpack build that automatically recompiles whenever index.js changes. The other thing it provides is an auto-generated index.html file that contains the standard html, head, and body tags, as well as a div with id 'root'. This root div is where the root component gets rendered, with a call like ReactDOM.render(YourExportedComponent, document.querySelector('#root')).

Exercise 1: Massive Refactoring

The code is too bloated. Please create a Hello component that renders “Hello” and a World component that renders “world!”. Then render them both, side-by-side, in that main component at the bottom.

Hint: You can basically write 2 new components that look very much like the existing one, assign them to variables Hello and World, and then refer to the components as <Hello/> <World/> in that bottom render function…

Type that up, hit Refresh (or not! react-heatpack comes with hot reloading!), and make sure it still works.

Give up? Click to see the answer.

Exercise 2: Make the components generic

It would be better if we could say hello to whoever we want. Modify the Worldcomponent to accept a prop called who. If who is provided, render that (with the exclamation point). If who is not provided, just render “world!”.

Hint: You can provide attributes when you use a React element, like <World who="Dave"/>. These attributes are called “props”, and inside the render function of World, they’re accessible under this.props, e.g. this.props.who.

If you have a JSX element (which is what <span>world!</span> is) and you want to perform an expression inside it, you can put that in single braces like <span>{this.props.who}!</span>. You can put conditionals like ? or || or && in there too – it’s just JavaScript – but it has to be a single expression.

Give up? Click to see the answer.

Exercise 3: Validate the inputs

Validate that the who prop passed to World is actually a string (leave it optional though).

Hint: React has an awesome thing called PropTypes that lets you define the type expected for each prop passed to a component.

If you’re used to Angular directives, and how they silently fail if you forgot to pass a required argument, this is pretty amazing stuff. Real actual error messages when you make a mistake!

PropTypes are defined on the component as a property like so:

React.createClass({
	propTypes: {
		name: React.PropTypes.string.isRequired,
		age: React.PropTypes.number, // optional
		parent: React.PropTypes.object.isRequired
	},
	render: function() {
		...
	}
})

When React renders this component, it will check the passed props and make sure they match propTypes. If they don’t, you’ll get a warning in the console.

Give up? Click to see the answer.

Exercise 4: Break it

Open up the browser console and then wreak some havoc! (watch the messages)

  • Try returning <Hello/><World/> from the main component at the bottom (take out the wrapping <div>)
  • Try passing a number to World like <World who={42}/>.
  • Try passing who={null}.
  • Try who={undefined}. Is it the same as not passing who at all?
  • Try making the who prop required, and try the above changes again.

Where to go from here

The React world is full of options. Redux, Reflux, Alt… react-router, redux-simple-router… Webpack, Babel, Browserify…

So which one should you learn next?

That’s a trick question: the answer, right now, is none of them. No, not even Redux.

Get your footing with plain React right now. Cement those concepts in your brain by writing more components, and wiring them together. Learn the PropTypes and use them in every component (this will save you lots of debugging time!).

You can actually get really far with plain React. Approach your first few apps from a “UI first” angle. In other words, don’t worry about fetching data from the server, saving records, etc. Start off with static data that you know the format of, and render that static data by composing React components.

This is powerful: once you realize that, given a fixed dataset, you can carve it up and render it perfectly, all you need to do is hook it up to real live data and it’ll all just work.

Want some ideas for small components to build for practice? I’ve got an article on that coming up soon! Sign up for my newsletter and you’ll get it when it’s out.

Learning React can be a struggle -- so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, read my book Pure React.

Loved it! Very well written and put together. Love that you focused only on React. Wish I had stumbled onto your book first before I messed around with all those scary "boilerplate" projects.

— John Lyon-Smith

Learn the basics of React in just 5 days

Finally understand how React works! You will:

? Get something on screen

? Write dynamic components

? Make it interactive

? Fetch real data

? Put it online

5 days, 5 emails. All free. Walk away with the basics & a plan!

Get Lesson 1 right now ?

 

 

Send Me Lesson 1

No spam, unsubscribe any time.

 

Previous Next

© 2018 Dave Ceddia.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值