Click here to Skip to main content
15,887,135 members
Articles / Web Development / React

3 Minute React Test Drive: Hello World the Easy Way

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
20 Apr 2016CPOL6 min read 11.8K  
3 minute react test drive

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 bullsh*t 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.
JavaScript
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 <a href="http://localhost:3000" target="_blank">http://localhost:3000</a> (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?

First, I want to mention that I have a newsletter that receives posts like this every week or so. If that sounds cool, click the button below to sign up.

HTML
<button class="cta-button" data-remodal-target="signup-modal">Send me more posts like this!</button>

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

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.
JavaScript
import React from 'react'

var Hello = React.createClass({
  render: function() {
    return <span>Hello</span>
  }
})

var World = React.createClass({
  render: function() {
    return <span>world!</span>
  }
})

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

Exercise 2: Make the Components Generic

It would be better if we could say hello to whoever we want. Modify the World component 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.
JavaScript
import React from 'react'

var Hello = React.createClass({
  render: function() {
    return <span>Hello</span>
  }
})

var World = React.createClass({
  render: function() {
    return <span>{this.props.who || 'world'}!</span>
  }
})

// Alternatively, use a ternary operator:
var World_v2 = React.createClass({
  render: function() {
    return <span>{this.props.who ? this.props.who : 'world'}!</span>
  }
})

// Or even split out the logic into its own function:
var World_v3 = React.createClass({
  getPerson: function() {
    return this.props.who || 'world';
  },

  render: function() {
    return <span>{this.getPerson()}!</span>
  }
})

export default React.createClass({
  render: function() {
    return <div><Hello/> <World who="Dave"/></div>
  }
})

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:

JavaScript
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.
JavaScript
import React from 'react'

var Hello = React.createClass({
  render: function() {
    return <span>Hello</span>
  }
})

var World = React.createClass({
  propTypes: {
    who: React.PropTypes.string
  },

  render: function() {
    return <span>{this.props.who || 'world'}!</span>
  }
})

export default React.createClass({
  render: function() {
    return <div><Hello/> <World who="Dave"/></div>
  }
})

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.

Learn React Piece by Piece

Webpack, Redux, and Flux? Oh my! Don't get overwhelmed. Get bite-size tutorials and learn more effectively.

3 Minute React Test Drive: Hello World the easy way was originally published by Dave Ceddia at Angularity on April 17, 2016.

This article was originally posted at https://daveceddia.com/feed.xml

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Dave is a Software Engineer in the Boston area and writes about AngularJS and other JavaScript things over at daveceddia.com

Comments and Discussions

 
-- There are no messages in this forum --