Steps to Create React App
The easiest way to get started on a new React project is by using a starter kit.
- Make sure you have a recent version of Node.js installed.
- Follow the installation instructions to create a new project.
npm create-react-app my-app cd my-app npm start
Create React App doesn’t handle backend logic or databases; it just creates a frontend build pipeline, so you can use it with any backend you want. It uses build tools like Babel and webpack under the hood, but works with zero configuration.
When you’re ready to deploy to production, running npm run build will create an optimized build of your app in the build folder. You can learn more about Create React App from its README and the User Guide.
Syntax Highlighting
Atom
Install language-babel package and follow the instructions.
Visual Studio Code
Install the sublime-babel-vscode extension and follow the instructions.
Developer Tools
The React Devtools extension for Chrome and Firefox lets you inspect a React component tree in your browser devtools.
Using a CDN
If you don’t want to use npm to manage client packages, the react
and react-dom
npm packages also provide single-file distributions in umd
folders. See the CDN page for links.
Specifying Attributes with JSX
You may use quotes to specify string literals as attributes:
const element = <div tabIndex="0"></div>;
You may also use curly braces to embed a JavaScript expression in an attribute:
const element = <img src={user.avatarUrl}></img>;
Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.
JSX Prevents Injection Attacks
It is safe to embed user input in JSX:
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;
By default, React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.
JSX Represents Objects
Babel compiles JSX down to React.createElement()
calls.
These two examples are identical:
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
React.createElement()
performs a few checks to help you write bug-free code but essentially it creates an object like this:
// Note: this structure is simplified
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
These objects are called “React elements”. You can think of them as descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.
Elements are the smallest building blocks of React apps.
An element describes what you want to see on the screen:
const element = <h1>Hello, world</h1>;
Unlike browser DOM elements, React elements are plain objects, and are cheap to create. React DOM takes care of updating the DOM to match the React elements.
Functional and Class Components
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
The simplest way to define a component is to write a JavaScript function:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “functional” because they are literally JavaScript functions.
You can also use an ES6 class to define a component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
The above two components are equivalent from React’s point of view.
Classes have some additional features that we will discuss in the next sections. Until then, we will use functional components for their conciseness.
Previously, we only encountered React elements that represent DOM tags:
const element = <div />;
However, elements can also represent user-defined components:
const element = <Welcome name="Sara" />;
When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”.
For example, this code renders “Hello, Sara” on the page:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
Note: Always start component names with a capital letter.
React treats components starting with lowercase letters as DOM tags. For example,
represents an HTML div tag, but represents a component and requires Welcome to be in scope.
Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum
function:
function sum(a, b) {
return a + b;
}
Such functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs.
Converting a Function to a Class
You can convert a functional component like Clock
to a class in five steps:
- Create an ES6 class, with the same name, that extends
React.Component
. - Add a single empty method to it called
render()
. - Move the body of the function into the
render()
method. - Replace
props
withthis.props
in therender()
body. - Delete the remaining empty function declaration.
You can use this lifecycle diagram as a cheat sheet.
Inline If with Logical && Operator
You may embed any expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical &&
operator. It can be handy for conditionally including an element:
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />,
document.getElementById('root')
);
Inline If-Else with Conditional Operator
Another method for conditionally rendering elements inline is to use the JavaScript conditional operator condition ? true : false
.
In the example below, we use it to conditionally render a small block of text.
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
Rendering Multiple Components
You can build collections of elements and include them in JSX using curly braces {}
.
Below, we loop through the numbers
array using the JavaScript map()
function. We return an <li>
element for each item. Finally, we assign the resulting array of elements to listItems
:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li>{number}</li>
);
We include the entire listItems
array inside a <ul>
element, and render it to the DOM:
ReactDOM.render(
<ul>{listItems}</ul>,
document.getElementById('root')
);