×

Welcome to Knowledge Base!

KB at your finger tips

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All
Web-React
Getting Started – React

Getting Started

This page is an overview of the React documentation and related resources.


React is a JavaScript library for building user interfaces. Learn what React is all about on our homepage or in the tutorial.





  • Try React

  • Learn React

  • Staying Informed

  • Versioned Documentation

  • Something Missing?


Try React


React has been designed from the start for gradual adoption, and you can use as little or as much React as you need. Whether you want to get a taste of React, add some interactivity to a simple HTML page, or start a complex React-powered app, the links in this section will help you get started.


Online Playgrounds


If you’re interested in playing around with React, you can use an online code playground. Try a Hello World template on CodePen, CodeSandbox, or Stackblitz.


If you prefer to use your own text editor, you can also download this HTML file, edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so we’d only recommend using this for simple demos.


Add React to a Website


You can add React to an HTML page in one minute. You can then either gradually expand its presence, or keep it contained to a few dynamic widgets.


Create a New React App


When starting a React project, a simple HTML page with script tags might still be the best option. It only takes a minute to set up!


As your application grows, you might want to consider a more integrated setup. There are several JavaScript toolchains we recommend for larger applications. Each of them can work with little to no configuration and lets you take full advantage of the rich React ecosystem. Learn how.


Learn React


People come to React from different backgrounds and with different learning styles. Whether you prefer a more theoretical or a practical approach, we hope you’ll find this section helpful.



  • If you prefer to learn by doing , start with our practical tutorial.

  • If you prefer to learn concepts step by step , start with our guide to main concepts.


Like any unfamiliar technology, React does have a learning curve. With practice and some patience, you will get the hang of it.


First Examples


The React homepage contains a few small React examples with a live editor. Even if you don’t know anything about React yet, try changing their code and see how it affects the result.


React for Beginners


If you feel that the React documentation goes at a faster pace than you’re comfortable with, check out this overview of React by Tania Rascia. It introduces the most important React concepts in a detailed, beginner-friendly way. Once you’re done, give the documentation another try!


React for Designers


If you’re coming from a design background, these resources are a great place to get started.


JavaScript Resources


The React documentation assumes some familiarity with programming in the JavaScript language. You don’t have to be an expert, but it’s harder to learn both React and JavaScript at the same time.


We recommend going through this JavaScript overview to check your knowledge level. It will take you between 30 minutes and an hour but you will feel more confident learning React.



Tip


Whenever you get confused by something in JavaScript, MDN and javascript.info are great websites to check. There are also community support forums where you can ask for help.



Practical Tutorial


If you prefer to learn by doing, check out our practical tutorial. In this tutorial, we build a tic-tac-toe game in React. You might be tempted to skip it because you’re not into building games — but give it a chance. The techniques you’ll learn in the tutorial are fundamental to building any React apps, and mastering it will give you a much deeper understanding.


Step-by-Step Guide


If you prefer to learn concepts step by step, our guide to main concepts is the best place to start. Every next chapter in it builds on the knowledge introduced in the previous chapters so you won’t miss anything as you go along.


Thinking in React


Many React users credit reading Thinking in React as the moment React finally “clicked” for them. It’s probably the oldest React walkthrough but it’s still just as relevant.



Sometimes people find third-party books and video courses more helpful than the official documentation. We maintain a list of commonly recommended resources, some of which are free.


Advanced Concepts


Once you’re comfortable with the main concepts and played with React a little bit, you might be interested in more advanced topics. This section will introduce you to the powerful, but less commonly used React features like context and refs.


API Reference


This documentation section is useful when you want to learn more details about a particular React API. For example, React.Component API reference can provide you with details on how setState() works, and what different lifecycle methods are useful for.


Glossary and FAQ


The glossary contains an overview of the most common terms you’ll see in the React documentation. There is also a FAQ section dedicated to short questions and answers about common topics, including making AJAX requests, component state, and file structure.


Staying Informed


The React blog is the official source for the updates from the React team. Anything important, including release notes or deprecation notices, will be posted there first.


You can also follow the @reactjs account on Twitter, but you won’t miss anything essential if you only read the blog.


Not every React release deserves its own blog post, but you can find a detailed changelog for every release in the CHANGELOG.md file in the React repository, as well as on the Releases page.


Versioned Documentation


This documentation always reflects the latest stable version of React. Since React 16, you can find older versions of the documentation on a separate page. Note that documentation for past versions is snapshotted at the time of the release, and isn’t being continuously updated.


Something Missing?


If something is missing in the documentation or if you found some part confusing, please file an issue for the documentation repository with your suggestions for improvement, or tweet at the @reactjs account. We love hearing from you!

Is this page useful? Edit this page
Read article
Add React to a Website – React

Add React to a Website

Use as little or as much React as you need.


React has been designed from the start for gradual adoption, and you can use as little or as much React as you need . Perhaps you only want to add some “sprinkles of interactivity” to an existing page. React components are a great way to do that.


The majority of websites aren’t, and don’t need to be, single-page apps. With a few lines of code and no build tooling , try React in a small part of your website. You can then either gradually expand its presence, or keep it contained to a few dynamic widgets.





Add React in One Minute


In this section, we will show how to add a React component to an existing HTML page. You can follow along with your own website, or create an empty HTML file to practice.


There will be no complicated tools or install requirements — to complete this section, you only need an internet connection, and a minute of your time.


Optional: Download the full example (2KB zipped)


Step 1: Add a DOM Container to the HTML


First, open the HTML page you want to edit. Add an empty <div> tag to mark the spot where you want to display something with React. For example:


<!-- ... existing HTML ... -->

<div id="like_button_container"></div>
<!-- ... existing HTML ... -->

We gave this <div> a unique id HTML attribute. This will allow us to find it from the JavaScript code later and display a React component inside of it.



Tip


You can place a “container” <div> like this anywhere inside the <body> tag. You may have as many independent DOM containers on one page as you need. They are usually empty — React will replace any existing content inside DOM containers.



Step 2: Add the Script Tags


Next, add three <script> tags to the HTML page right before the closing </body> tag:


  <!-- ... other HTML ... -->

<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>

The first two tags load React. The third one will load your component code.


Step 3: Create a React Component


Create a file called like_button.js next to your HTML page.


Open this starter code and paste it into the file you created.



Tip


This code defines a React component called LikeButton . Don’t worry if you don’t understand it yet — we’ll cover the building blocks of React later in our hands-on tutorial and main concepts guide. For now, let’s just get it showing on the screen!



After the starter code , add three lines to the bottom of like_button.js :


// ... the starter code you pasted ...

const domContainer = document.querySelector('#like_button_container');const root = ReactDOM.createRoot(domContainer);root.render(e(LikeButton));

These three lines of code find the <div> we added to our HTML in the first step, create a React app with it, and then display our “Like” button React component inside of it.


That’s It!


There is no step four. You have just added the first React component to your website.


Check out the next sections for more tips on integrating React.


View the full example source code


Download the full example (2KB zipped)


Tip: Reuse a Component


Commonly, you might want to display React components in multiple places on the HTML page. Here is an example that displays the “Like” button three times and passes some data to it:


View the full example source code


Download the full example (2KB zipped)



Note


This strategy is mostly useful while React-powered parts of the page are isolated from each other. Inside React code, it’s easier to use component composition instead.



Tip: Minify JavaScript for Production


Before deploying your website to production, be mindful that unminified JavaScript can significantly slow down the page for your users.


If you already minify the application scripts, your site will be production-ready if you ensure that the deployed HTML loads the versions of React ending in production.min.js :


<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>

If you don’t have a minification step for your scripts, here’s one way to set it up.


Optional: Try React with JSX


In the examples above, we only relied on features that are natively supported by browsers. This is why we used a JavaScript function call to tell React what to display:


const e = React.createElement;

// Display a "Like" <button>
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);

However, React also offers an option to use JSX instead:


// Display a "Like" <button>
return (
<button onClick={() => this.setState({ liked: true })}>
Like
</button>
);

These two code snippets are equivalent. While JSX is completely optional , many people find it helpful for writing UI code — both with React and with other libraries.


You can play with JSX using this online converter.


Quickly Try JSX


The quickest way to try JSX in your project is to add this <script> tag to your page:


<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it. Here is an example HTML file with JSX that you can download and play with.


This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production . When you’re ready to move forward, remove this new <script> tag and the type="text/babel" attributes you’ve added. Instead, in the next section you will set up a JSX preprocessor to convert all your <script> tags automatically.


Add JSX to a Project


Adding JSX to a project doesn’t require complicated tools like a bundler or a development server. Essentially, adding JSX is a lot like adding a CSS preprocessor. The only requirement is to have Node.js installed on your computer.


Go to your project folder in the terminal, and paste these two commands:



  1. Step 1: Run npm init -y (if it fails, here’s a fix)

  2. Step 2: Run npm install babel-cli@6 babel-preset-react-app@3



Tip


We’re using npm here only to install the JSX preprocessor; you won’t need it for anything else. Both React and the application code can stay as <script> tags with no changes.



Congratulations! You just added a production-ready JSX setup to your project.


Run JSX Preprocessor


Create a folder called src and run this terminal command:


npx babel --watch src --out-dir . --presets react-app/prod


Note


npx is not a typo — it’s a package runner tool that comes with npm 5.2+.


If you see an error message saying “You have mistakenly installed the babel package”, you might have missed the previous step. Perform it in the same folder, and then try again.



Don’t wait for it to finish — this command starts an automated watcher for JSX.


If you now create a file called src/like_button.js with this JSX starter code , the watcher will create a preprocessed like_button.js with the plain JavaScript code suitable for the browser. When you edit the source file with JSX, the transform will re-run automatically.


As a bonus, this also lets you use modern JavaScript syntax features like classes without worrying about breaking older browsers. The tool we just used is called Babel, and you can learn more about it from its documentation.


If you notice that you’re getting comfortable with build tools and want them to do more for you, the next section describes some of the most popular and approachable toolchains. If not — those script tags will do just fine!

Is this page useful? Edit this page
Read article
Create a New React App – React

Create a New React App

Use an integrated toolchain for the best user and developer experience.


This page describes a few popular React toolchains which help with tasks like:



  • Scaling to many files and components.

  • Using third-party libraries from npm.

  • Detecting common mistakes early.

  • Live-editing CSS and JS in development.

  • Optimizing the output for production.


The toolchains recommended on this page don’t require configuration to get started .


You Might Not Need a Toolchain


If you don’t experience the problems described above or don’t feel comfortable using JavaScript tools yet, consider adding React as a plain <script> tag on an HTML page, optionally with JSX.


This is also the easiest way to integrate React into an existing website. You can always add a larger toolchain if you find it helpful!



The React team primarily recommends these solutions:



  • If you’re learning React or creating a new single-page app, use Create React App.

  • If you’re building a server-rendered website with Node.js, try Next.js.

  • If you’re building a static content-oriented website, try Gatsby.

  • If you’re building a component library or integrating with an existing codebase , try More Flexible Toolchains.


Create React App


Create React App is a comfortable environment for learning React , and is the best way to start building a new single-page application in React.


It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production. You’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine. To create a project, run:


npx create-react-app my-app
cd my-app
npm start


Note


npx on the first line is not a typo — it’s a package runner tool that comes with npm 5.2+.



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. Under the hood, it uses Babel and webpack, but you don’t need to know anything about them.


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.


Next.js


Next.js is a popular and lightweight framework for static and server‑rendered applications built with React. It includes styling and routing solutions out of the box, and assumes that you’re using Node.js as the server environment.


Learn Next.js from its official guide.


Gatsby


Gatsby is the best way to create static websites with React. It lets you use React components, but outputs pre-rendered HTML and CSS to guarantee the fastest load time.


Learn Gatsby from its official guide and a gallery of starter kits.


More Flexible Toolchains


The following toolchains offer more flexibility and choice. We recommend them to more experienced users:



  • Neutrino combines the power of webpack with the simplicity of presets, and includes a preset for React apps and React components.

  • Nx is a toolkit for full-stack monorepo development, with built-in support for React, Next.js, Express, and more.

  • Parcel is a fast, zero configuration web application bundler that works with React.

  • Razzle is a server-rendering framework that doesn’t require any configuration, but offers more flexibility than Next.js.


Creating a Toolchain from Scratch


A JavaScript build toolchain typically consists of:



  • A package manager , such as Yarn or npm. It lets you take advantage of a vast ecosystem of third-party packages, and easily install or update them.

  • A bundler , such as webpack or Parcel. It lets you write modular code and bundle it together into small packages to optimize load time.

  • A compiler such as Babel. It lets you write modern JavaScript code that still works in older browsers.


If you prefer to set up your own JavaScript toolchain from scratch, check out this guide that re-creates some of the Create React App functionality.


Don’t forget to ensure your custom toolchain is correctly set up for production.

Is this page useful? Edit this page
Read article
CDN Links – React

CDN Links

Both React and ReactDOM are available over a CDN.


<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

The versions above are only meant for development, and are not suitable for production. Minified and optimized production versions of React are available at:


<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>

To load a specific version of react and react-dom , replace 18 with the version number.


Why the crossorigin Attribute?


If you serve React from a CDN, we recommend to keep the crossorigin attribute set:


<script crossorigin src="..."></script>

We also recommend to verify that the CDN you are using sets the Access-Control-Allow-Origin: * HTTP header:







Access-Control-Allow-Origin: *





This enables a better error handling experience in React 16 and later.

Is this page useful? Edit this page
Read article
Release Channels – React

Release Channels

React relies on a thriving open source community to file bug reports, open pull requests, and submit RFCs. To encourage feedback we sometimes share special builds of React that include unreleased features.



This document will be most relevant to developers who work on frameworks, libraries, or developer tooling. Developers who use React primarily to build user-facing applications should not need to worry about our prerelease channels.



Each of React’s release channels is designed for a distinct use case:



  • Latest is for stable, semver React releases. It’s what you get when you install React from npm. This is the channel you’re already using today. Use this for all user-facing React applications.

  • Next tracks the main branch of the React source code repository. Think of these as release candidates for the next minor semver release. Use this for integration testing between React and third party projects.

  • Experimental includes experimental APIs and features that aren’t available in the stable releases. These also track the main branch, but with additional feature flags turned on. Use this to try out upcoming features before they are released.


All releases are published to npm, but only Latest uses semantic versioning. Prereleases (those in the Next and Experimental channels) have versions generated from a hash of their contents and the commit date, e.g. 0.0.0-68053d940-20210623 for Next and 0.0.0-experimental-68053d940-20210623 for Experimental.


The only officially supported release channel for user-facing applications is Latest . Next and Experimental releases are provided for testing purposes only, and we provide no guarantees that behavior won’t change between releases. They do not follow the semver protocol that we use for releases from Latest.


By publishing prereleases to the same registry that we use for stable releases, we are able to take advantage of the many tools that support the npm workflow, like unpkg and CodeSandbox.


Latest Channel


Latest is the channel used for stable React releases. It corresponds to the latest tag on npm. It is the recommended channel for all React apps that are shipped to real users.


If you’re not sure which channel you should use, it’s Latest. If you’re a React developer, this is what you’re already using.


You can expect updates to Latest to be extremely stable. Versions follow the semantic versioning scheme. Learn more about our commitment to stability and incremental migration in our versioning policy.


Next Channel


The Next channel is a prerelease channel that tracks the main branch of the React repository. We use prereleases in the Next channel as release candidates for the Latest channel. You can think of Next as a superset of Latest that is updated more frequently.


The degree of change between the most recent Next release and the most recent Latest release is approximately the same as you would find between two minor semver releases. However, the Next channel does not conform to semantic versioning. You should expect occasional breaking changes between successive releases in the Next channel.


Do not use prereleases in user-facing applications.


Releases in Next are published with the next tag on npm. Versions are generated from a hash of the build’s contents and the commit date, e.g. 0.0.0-68053d940-20210623 .


Using the Next Channel for Integration Testing


The Next channel is designed to support integration testing between React and other projects.


All changes to React go through extensive internal testing before they are released to the public. However, there are a myriad of environments and configurations used throughout the React ecosystem, and it’s not possible for us to test against every single one.


If you’re the author of a third party React framework, library, developer tool, or similar infrastructure-type project, you can help us keep React stable for your users and the entire React community by periodically running your test suite against the most recent changes. If you’re interested, follow these steps:



  • Set up a cron job using your preferred continuous integration platform. Cron jobs are supported by both CircleCI and Travis CI.


  • In the cron job, update your React packages to the most recent React release in the Next channel, using next tag on npm. Using the npm cli:


    npm update react@next react-dom@next

    Or yarn:


    yarn upgrade react@next react-dom@next


  • Run your test suite against the updated packages.

  • If everything passes, great! You can expect that your project will work with the next minor React release.

  • If something breaks unexpectedly, please let us know by filing an issue.


A project that uses this workflow is Next.js. (No pun intended! Seriously!) You can refer to their CircleCI configuration as an example.


Experimental Channel


Like Next, the Experimental channel is a prerelease channel that tracks the main branch of the React repository. Unlike Next, Experimental releases include additional features and APIs that are not ready for wider release.


Usually, an update to Next is accompanied by a corresponding update to Experimental. They are based on the same source revision, but are built using a different set of feature flags.


Experimental releases may be significantly different than releases to Next and Latest. Do not use Experimental releases in user-facing applications. You should expect frequent breaking changes between releases in the Experimental channel.


Releases in Experimental are published with the experimental tag on npm. Versions are generated from a hash of the build’s contents and the commit date, e.g. 0.0.0-experimental-68053d940-20210623 .


What Goes Into an Experimental Release?


Experimental features are ones that are not ready to be released to the wider public, and may change drastically before they are finalized. Some experiments may never be finalized — the reason we have experiments is to test the viability of proposed changes.


For example, if the Experimental channel had existed when we announced Hooks, we would have released Hooks to the Experimental channel weeks before they were available in Latest.


You may find it valuable to run integration tests against Experimental. This is up to you. However, be advised that Experimental is even less stable than Next. We do not guarantee any stability between Experimental releases.


How Can I Learn More About Experimental Features?


Experimental features may or may not be documented. Usually, experiments aren’t documented until they are close to shipping in Next or Latest.


If a feature is not documented, they may be accompanied by an RFC.


We will post to the React blog when we’re ready to announce new experiments, but that doesn’t mean we will publicize every experiment.


You can always refer to our public GitHub repository’s history for a comprehensive list of changes.

Is this page useful? Edit this page
Read article
Hello World – React

Hello World

The smallest React example looks like this:


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);

It displays a heading saying “Hello, world!” on the page.


Try it on CodePen


Click the link above to open an online editor. Feel free to make some changes, and see how they affect the output. Most pages in this guide will have editable examples like this one.


How to Read This Guide


In this guide, we will examine the building blocks of React apps: elements and components. Once you master them, you can create complex apps from small reusable pieces.



Tip


This guide is designed for people who prefer learning concepts step by step . If you prefer to learn by doing, check out our practical tutorial. You might find this guide and the tutorial complementary to each other.



This is the first chapter in a step-by-step guide about main React concepts. You can find a list of all its chapters in the navigation sidebar. If you’re reading this from a mobile device, you can access the navigation by pressing the button in the bottom right corner of your screen.


Every chapter in this guide builds on the knowledge introduced in earlier chapters. You can learn most of React by reading the “Main Concepts” guide chapters in the order they appear in the sidebar. For example, “Introducing JSX” is the next chapter after this one.


Knowledge Level Assumptions


React is a JavaScript library, and so we’ll assume you have a basic understanding of the JavaScript language. If you don’t feel very confident, we recommend going through a JavaScript tutorial to check your knowledge level and enable you to follow along this guide without getting lost. It might take you between 30 minutes and an hour, but as a result you won’t have to feel like you’re learning both React and JavaScript at the same time.



Note


This guide occasionally uses some newer JavaScript syntax in the examples. If you haven’t worked with JavaScript in the last few years, these three points should get you most of the way.



Let’s Get Started!


Keep scrolling down, and you’ll find the link to the next chapter of this guide right before the website footer.

Is this page useful? Edit this page
Read article
Introducing JSX – React

Introducing JSX

Consider this variable declaration:


const element = <h1>Hello, world!</h1>;

This funny tag syntax is neither a string nor HTML.


It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.


JSX produces React “elements”. We will explore rendering them to the DOM in the next section. Below, you can find the basics of JSX necessary to get you started.


Why JSX?


React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.


Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. We will come back to components in a further section, but if you’re not yet comfortable putting markup in JS, this talk might convince you otherwise.


React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.


With that out of the way, let’s get started!


Embedding Expressions in JSX


In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces:


const name = 'Josh Perez';const element = <h1>Hello, {name}</h1>;

You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2 , user.firstName , or formatName(user) are all valid JavaScript expressions.


In the example below, we embed the result of calling a JavaScript function, formatName(user) , into an <h1> element.


function formatName(user) {
return user.firstName + ' ' + user.lastName;
}

const user = {
firstName: 'Harper',
lastName: 'Perez'
};

const element = (
<h1>
Hello, {formatName(user)}! </h1>
);

Try it on CodePen


We split JSX over multiple lines for readability. While it isn’t required, when doing this, we also recommend wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.


JSX is an Expression Too


After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.


This means that you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions:


function getGreeting(user) {
if (user) {
return <h1>Hello, {formatName(user)}!</h1>; }
return <h1>Hello, Stranger.</h1>;}

Specifying Attributes with JSX


You may use quotes to specify string literals as attributes:


const element = <a href="https://www.reactjs.org"> link </a>;

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.



Warning:


Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.


For example, class becomes className in JSX, and tabindex becomes tabIndex .



Specifying Children with JSX


If a tag is empty, you may close it immediately with /> , like XML:


const element = <img src={user.avatarUrl} />;

JSX tags may contain children:


const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);

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.


We will explore rendering React elements to the DOM in the next section.



Tip:


We recommend using the “Babel” language definition for your editor of choice so that both ES6 and JSX code is properly highlighted.


Is this page useful? Edit this page
Read article
Rendering Elements – React

Rendering Elements

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.



Note:


One might confuse elements with a more widely known concept of “components”. We will introduce components in the next section. Elements are what components are “made of”, and we encourage you to read this section before jumping ahead.



Rendering an Element into the DOM


Let’s say there is a <div> somewhere in your HTML file:


<div id="root"></div>

We call this a “root” DOM node because everything inside it will be managed by React DOM.


Applications built with just React usually have a single root DOM node. If you are integrating React into an existing app, you may have as many isolated root DOM nodes as you like.


To render a React element, first pass the DOM element to ReactDOM.createRoot() , then pass the React element to root.render() :



const root = ReactDOM.createRoot(
document.getElementById('root')
);
const element = <h1>Hello, world</h1>;
root.render(element);


Try it on CodePen


It displays “Hello, world” on the page.


Updating the Rendered Element


React elements are immutable. Once you create an element, you can’t change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.


With our knowledge so far, the only way to update the UI is to create a new element, and pass it to root.render() .


Consider this ticking clock example:



const root = ReactDOM.createRoot(
document.getElementById('root')
);

function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
root.render(element);}

setInterval(tick, 1000);


Try it on CodePen


It calls root.render() every second from a setInterval() callback.



Note:


In practice, most React apps only call root.render() once. In the next sections we will learn how such code gets encapsulated into stateful components.


We recommend that you don’t skip topics because they build on each other.



React Only Updates What’s Necessary


React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.


You can verify by inspecting the last example with the browser tools:


DOM inspector showing granular updates


Even though we create an element describing the whole UI tree on every tick, only the text node whose contents have changed gets updated by React DOM.


In our experience, thinking about how the UI should look at any given moment, rather than how to change it over time, eliminates a whole class of bugs.

Is this page useful? Edit this page
Read article
Components and Props – React

Components and Props

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components. You can find a detailed component API reference here.


Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.


Function and Class Components


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 “function components” 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.


Function and Class components both have some additional features that we will discuss in the next sections.


Rendering a Component


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 and children 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 root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;root.render(element);

Try it on CodePen


Let’s recap what happens in this example:



  1. We call root.render() with the <Welcome name="Sara" /> element.

  2. React calls the Welcome component with {name: 'Sara'} as the props.

  3. Our Welcome component returns a <h1>Hello, Sara</h1> element as the result.

  4. React DOM efficiently updates the DOM to match <h1>Hello, Sara</h1> .



Note: Always start component names with a capital letter.


React treats components starting with lowercase letters as DOM tags. For example, <div /> represents an HTML div tag, but <Welcome /> represents a component and requires Welcome to be in scope.


To learn more about the reasoning behind this convention, please read JSX In Depth.



Composing Components


Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.


For example, we can create an App component that renders Welcome many times:


function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

function App() {
return (
<div>
<Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome name="Edite" /> </div>
);
}

Try it on CodePen


Typically, new React apps have a single App component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like Button and gradually work your way to the top of the view hierarchy.


Extracting Components


Don’t be afraid to split components into smaller components.


For example, consider this Comment component:


function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>

<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}

Try it on CodePen


It accepts author (an object), text (a string), and date (a date) as props, and describes a comment on a social media website.


This component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let’s extract a few components from it.


First, we will extract Avatar :


function Avatar(props) {
return (
<img className="Avatar" src={props.user.avatarUrl} alt={props.user.name} /> );
}

The Avatar doesn’t need to know that it is being rendered inside a Comment . This is why we have given its prop a more generic name: user rather than author .


We recommend naming props from the component’s own point of view rather than the context in which it is being used.


We can now simplify Comment a tiny bit:


function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<Avatar user={props.author} /> <div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}

Next, we will extract a UserInfo component that renders an Avatar next to the user’s name:


function UserInfo(props) {
return (
<div className="UserInfo"> <Avatar user={props.user} /> <div className="UserInfo-name"> {props.user.name} </div> </div> );
}

This lets us simplify Comment even further:


function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} /> <div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}

Try it on CodePen


Extracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps. A good rule of thumb is that if a part of your UI is used several times ( Button , Panel , Avatar ), or is complex enough on its own ( App , FeedStory , Comment ), it is a good candidate to be extracted to a separate component.


Props are Read-Only


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.


In contrast, this function is impure because it changes its own input:


function withdraw(account, amount) {
account.total -= amount;
}

React is pretty flexible but it has a single strict rule:


All React components must act like pure functions with respect to their props.


Of course, application UIs are dynamic and change over time. In the next section, we will introduce a new concept of “state”. State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

Is this page useful? Edit this page
Read article
State and Lifecycle – React

State and Lifecycle

This page introduces the concept of state and lifecycle in a React component. You can find a detailed component API reference here.


Consider the ticking clock example from one of the previous sections. In Rendering Elements, we have only learned one way to update the UI. We call root.render() to change the rendered output:


const root = ReactDOM.createRoot(document.getElementById('root'));

function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
root.render(element);}

setInterval(tick, 1000);

Try it on CodePen


In this section, we will learn how to make the Clock component truly reusable and encapsulated. It will set up its own timer and update itself every second.


We can start by encapsulating how the clock looks:


const root = ReactDOM.createRoot(document.getElementById('root'));

function Clock(props) {
return (
<div> <h1>Hello, world!</h1> <h2>It is {props.date.toLocaleTimeString()}.</h2> </div> );
}

function tick() {
root.render(<Clock date={new Date()} />);}

setInterval(tick, 1000);

Try it on CodePen


However, it misses a crucial requirement: the fact that the Clock sets up a timer and updates the UI every second should be an implementation detail of the Clock .


Ideally we want to write this once and have the Clock update itself:


root.render(<Clock />);

To implement this, we need to add “state” to the Clock component.


State is similar to props, but it is private and fully controlled by the component.


Converting a Function to a Class


You can convert a function component like Clock to a class in five steps:



  1. Create an ES6 class, with the same name, that extends React.Component .

  2. Add a single empty method to it called render() .

  3. Move the body of the function into the render() method.

  4. Replace props with this.props in the render() body.

  5. Delete the remaining empty function declaration.


class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

Try it on CodePen


Clock is now defined as a class rather than a function.


The render method will be called each time an update happens, but as long as we render <Clock /> into the same DOM node, only a single instance of the Clock class will be used. This lets us use additional features such as local state and lifecycle methods.


Adding Local State to a Class


We will move the date from props to state in three steps:



  1. Replace this.props.date with this.state.date in the render() method:


class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div>
);
}
}


  1. Add a class constructor that assigns the initial this.state :


class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()}; }

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

Note how we pass props to the base constructor:


  constructor(props) {
super(props); this.state = {date: new Date()};
}

Class components should always call the base constructor with props .



  1. Remove the date prop from the <Clock /> element:


root.render(<Clock />);

We will later add the timer code back to the component itself.


The result looks like this:


class Clock extends React.Component {
constructor(props) { super(props); this.state = {date: new Date()}; }
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div>
);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);

Try it on CodePen


Next, we’ll make the Clock set up its own timer and update itself every second.


Adding Lifecycle Methods to a Class


In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.


We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.


We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.


We can declare special methods on the component class to run some code when a component mounts and unmounts:


class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

componentDidMount() { }
componentWillUnmount() { }
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

These methods are called “lifecycle methods”.


The componentDidMount() method runs after the component output has been rendered to the DOM. This is a good place to set up a timer:


  componentDidMount() {
this.timerID = setInterval( () => this.tick(), 1000 ); }

Note how we save the timer ID right on this ( this.timerID ).


While this.props is set up by React itself and this.state has a special meaning, you are free to add additional fields to the class manually if you need to store something that doesn’t participate in the data flow (like a timer ID).


We will tear down the timer in the componentWillUnmount() lifecycle method:


  componentWillUnmount() {
clearInterval(this.timerID); }

Finally, we will implement a method called tick() that the Clock component will run every second.


It will use this.setState() to schedule updates to the component local state:


class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

tick() { this.setState({ date: new Date() }); }
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);

Try it on CodePen


Now the clock ticks every second.


Let’s quickly recap what’s going on and the order in which the methods are called:



  1. When <Clock /> is passed to root.render() , React calls the constructor of the Clock component. Since Clock needs to display the current time, it initializes this.state with an object including the current time. We will later update this state.

  2. React then calls the Clock component’s render() method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Clock ’s render output.

  3. When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle method. Inside it, the Clock component asks the browser to set up a timer to call the component’s tick() method once a second.

  4. Every second the browser calls the tick() method. Inside it, the Clock component schedules a UI update by calling setState() with an object containing the current time. Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen. This time, this.state.date in the render() method will be different, and so the render output will include the updated time. React updates the DOM accordingly.

  5. If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle method so the timer is stopped.


Using State Correctly


There are three things you should know about setState() .


Do Not Modify State Directly


For example, this will not re-render a component:


// Wrong
this.state.comment = 'Hello';

Instead, use setState() :


// Correct
this.setState({comment: 'Hello'});

The only place where you can assign this.state is the constructor.


State Updates May Be Asynchronous


React may batch multiple setState() calls into a single update for performance.


Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.


For example, this code may fail to update the counter:


// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:


// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));

We used an arrow function above, but it also works with regular functions:


// Correct
this.setState(function(state, props) {
return {
counter: state.counter + props.increment
};
});

State Updates are Merged


When you call setState() , React merges the object you provide into the current state.


For example, your state may contain several independent variables:


  constructor(props) {
super(props);
this.state = {
posts: [], comments: [] };
}

Then you can update them independently with separate setState() calls:


  componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts });
});

fetchComments().then(response => {
this.setState({
comments: response.comments });
});
}

The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments .


The Data Flows Down


Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn’t care whether it is defined as a function or a class.


This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it.


A component may choose to pass its state down as props to its child components:


<FormattedDate date={this.state.date} />

The FormattedDate component would receive the date in its props and wouldn’t know whether it came from the Clock ’s state, from the Clock ’s props, or was typed by hand:


function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

Try it on CodePen


This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.


If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.


To show that all components are truly isolated, we can create an App component that renders three <Clock> s:


function App() {
return (
<div>
<Clock /> <Clock /> <Clock /> </div>
);
}

Try it on CodePen


Each Clock sets up its own timer and updates independently.


In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.

Is this page useful? Edit this page
Read article

Still Thinking?
Give us a try!

We embrace agility in everything we do.
Our onboarding process is both simple and meaningful.
We can't wait to welcome you on AiDOOS!