Movatterモバイル変換


[0]ホーム

URL:


Join us for React Conf on Oct 7-8.
Learn more.

Is this page useful?

Quick Start

Welcome to the React documentation! This page will give you an introduction to 80% of the React concepts that you will use on a daily basis.

You will learn

  • How to create and nest components
  • How to add markup and styles
  • How to display data
  • How to render conditions and lists
  • How to respond to events and update the screen
  • How to share data between components

Creating and nesting components

React apps are made out ofcomponents. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.

React components are JavaScript functions that return markup:

functionMyButton(){
return(
<button>I'm a button</button>
);
}

Now that you’ve declaredMyButton, you can nest it into another component:

exportdefaultfunctionMyApp(){
return(
<div>
<h1>Welcome to my app</h1>
<MyButton/>
</div>
);
}

Notice that<MyButton /> starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase.

Have a look at the result:

Fork
functionMyButton(){return(<button>      I'm a button</button>);}exportdefaultfunctionMyApp(){return(<div><h1>Welcome to my app</h1><MyButton/></div>);}

Theexport default keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax,MDN andjavascript.info have great references.

Writing markup with JSX

The markup syntax you’ve seen above is calledJSX. It is optional, but most React projects use JSX for its convenience. All of thetools we recommend for local development support JSX out of the box.

JSX is stricter than HTML. You have to close tags like<br />. Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a<div>...</div> or an empty<>...</> wrapper:

functionAboutPage(){
return(
<>
<h1>About</h1>
<p>Hello there.<br/>How do you do?</p>
</>
);
}

If you have a lot of HTML to port to JSX, you can use anonline converter.

Adding styles

In React, you specify a CSS class withclassName. It works the same way as the HTMLclass attribute:

<imgclassName="avatar"/>

Then you write the CSS rules for it in a separate CSS file:

/* In your CSS */
.avatar{
border-radius:50%;
}

React does not prescribe how you add CSS files. In the simplest case, you’ll add a<link> tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.

Displaying data

JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will displayuser.name:

return(
<h1>
{user.name}
</h1>
);

You can also “escape into JavaScript” from JSX attributes, but you have to use curly bracesinstead of quotes. For example,className="avatar" passes the"avatar" string as the CSS class, butsrc={user.imageUrl} reads the JavaScriptuser.imageUrl variable value, and then passes that value as thesrc attribute:

return(
<img
className="avatar"
src={user.imageUrl}
/>
);

You can put more complex expressions inside the JSX curly braces too, for example,string concatenation:

Fork
constuser ={name:'Hedy Lamarr',imageUrl:'https://i.imgur.com/yXOvdOSs.jpg',imageSize:90,};exportdefaultfunctionProfile(){return(<><h1>{user.name}</h1><imgclassName="avatar"src={user.imageUrl}alt={'Photo of ' +user.name}style={{width:user.imageSize,height:user.imageSize}}/></>);}

In the above example,style={{}} is not a special syntax, but a regular{} object inside thestyle={ } JSX curly braces. You can use thestyle attribute when your styles depend on JavaScript variables.

Conditional rendering

In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use anif statement to conditionally include JSX:

letcontent;
if(isLoggedIn){
content =<AdminPanel/>;
}else{
content =<LoginForm/>;
}
return(
<div>
{content}
</div>
);

If you prefer more compact code, you can use theconditional? operator. Unlikeif, it works inside JSX:

<div>
{isLoggedIn ?(
<AdminPanel/>
) :(
<LoginForm/>
)}
</div>

When you don’t need theelse branch, you can also use a shorterlogical&& syntax:

<div>
{isLoggedIn &&<AdminPanel/>}
</div>

All of these approaches also work for conditionally specifying attributes. If you’re unfamiliar with some of this JavaScript syntax, you can start by always usingif...else.

Rendering lists

You will rely on JavaScript features likefor loop and thearraymap() function to render lists of components.

For example, let’s say you have an array of products:

constproducts =[
{title:'Cabbage',id:1},
{title:'Garlic',id:2},
{title:'Apple',id:3},
];

Inside your component, use themap() function to transform an array of products into an array of<li> items:

constlistItems =products.map(product=>
<likey={product.id}>
{product.title}
</li>
);

return(
<ul>{listItems}</ul>
);

Notice how<li> has akey attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items.

Fork
constproducts =[{title:'Cabbage',isFruit:false,id:1},{title:'Garlic',isFruit:false,id:2},{title:'Apple',isFruit:true,id:3},];exportdefaultfunctionShoppingList(){constlistItems =products.map(product=><likey={product.id}style={{color:product.isFruit ?'magenta' :'darkgreen'}}>{product.title}</li>);return(<ul>{listItems}</ul>);}

Responding to events

You can respond to events by declaringevent handler functions inside your components:

functionMyButton(){
functionhandleClick(){
alert('You clicked me!');
}

return(
<buttononClick={handleClick}>
Click me
</button>
);
}

Notice howonClick={handleClick} has no parentheses at the end! Do notcall the event handler function: you only need topass it down. React will call your event handler when the user clicks the button.

Updating the screen

Often, you’ll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, addstate to your component.

First, importuseState from React:

import{useState}from'react';

Now you can declare astate variable inside your component:

functionMyButton(){
const[count,setCount] =useState(0);
// ...

You’ll get two things fromuseState: the current state (count), and the function that lets you update it (setCount). You can give them any names, but the convention is to write[something, setSomething].

The first time the button is displayed,count will be0 because you passed0 touseState(). When you want to change state, callsetCount() and pass the new value to it. Clicking this button will increment the counter:

functionMyButton(){
const[count,setCount] =useState(0);

functionhandleClick(){
setCount(count +1);
}

return(
<buttononClick={handleClick}>
Clicked{count} times
</button>
);
}

React will call your component function again. This time,count will be1. Then it will be2. And so on.

If you render the same component multiple times, each will get its own state. Click each button separately:

Fork
import{useState}from'react';exportdefaultfunctionMyApp(){return(<div><h1>Counters that update separately</h1><MyButton/><MyButton/></div>);}functionMyButton(){const[count,setCount] =useState(0);functionhandleClick(){setCount(count +1);}return(<buttononClick={handleClick}>      Clicked{count} times</button>);}

Notice how each button “remembers” its owncount state and doesn’t affect other buttons.

Using Hooks

Functions starting withuse are calledHooks.useState is a built-in Hook provided by React. You can find other built-in Hooks in theAPI reference. You can also write your own Hooks by combining the existing ones.

Hooks are more restrictive than other functions. You can only call Hooksat the top of your components (or other Hooks). If you want to useuseState in a condition or a loop, extract a new component and put it there.

Sharing data between components

In the previous example, eachMyButton had its own independentcount, and when each button was clicked, only thecount for the button clicked changed:

Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. Both MyButton components contain a count with value zero.
Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. Both MyButton components contain a count with value zero.

Initially, eachMyButton’scount state is0

The same diagram as the previous, with the count of the first child MyButton component highlighted indicating a click with the count value incremented to one. The second MyButton component still contains value zero.
The same diagram as the previous, with the count of the first child MyButton component highlighted indicating a click with the count value incremented to one. The second MyButton component still contains value zero.

The firstMyButton updates itscount to1

However, often you’ll need components toshare data and always update together.

To make bothMyButton components display the samecount and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them.

In this example, it isMyApp:

Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. MyApp contains a count value of zero which is passed down to both of the MyButton components, which also show value zero.
Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. MyApp contains a count value of zero which is passed down to both of the MyButton components, which also show value zero.

Initially,MyApp’scount state is0 and is passed down to both children

The same diagram as the previous, with the count of the parent MyApp component highlighted indicating a click with the value incremented to one. The flow to both of the children MyButton components is also highlighted, and the count value in each child is set to one indicating the value was passed down.
The same diagram as the previous, with the count of the parent MyApp component highlighted indicating a click with the value incremented to one. The flow to both of the children MyButton components is also highlighted, and the count value in each child is set to one indicating the value was passed down.

On click,MyApp updates itscount state to1 and passes it down to both children

Now when you click either button, thecount inMyApp will change, which will change both of the counts inMyButton. Here’s how you can express this in code.

First,move the state up fromMyButton intoMyApp:

exportdefaultfunctionMyApp(){
const[count,setCount] =useState(0);

functionhandleClick(){
setCount(count +1);
}

return(
<div>
<h1>Counters that update separately</h1>
<MyButton/>
<MyButton/>
</div>
);
}

functionMyButton(){
// ... we're moving code from here ...
}

Then,pass the state down fromMyApp to eachMyButton, together with the shared click handler. You can pass information toMyButton using the JSX curly braces, just like you previously did with built-in tags like<img>:

exportdefaultfunctionMyApp(){
const[count,setCount] =useState(0);

functionhandleClick(){
setCount(count +1);
}

return(
<div>
<h1>Counters that update together</h1>
<MyButtoncount={count}onClick={handleClick}/>
<MyButtoncount={count}onClick={handleClick}/>
</div>
);
}

The information you pass down like this is calledprops. Now theMyApp component contains thecount state and thehandleClick event handler, andpasses both of them down as props to each of the buttons.

Finally, changeMyButton toread the props you have passed from its parent component:

functionMyButton({count,onClick}){
return(
<buttononClick={onClick}>
Clicked{count} times
</button>
);
}

When you click the button, theonClick handler fires. Each button’sonClick prop was set to thehandleClick function insideMyApp, so the code inside of it runs. That code callssetCount(count + 1), incrementing thecount state variable. The newcount value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”. By moving state up, you’ve shared it between components.

Fork
import{useState}from'react';exportdefaultfunctionMyApp(){const[count,setCount] =useState(0);functionhandleClick(){setCount(count +1);}return(<div><h1>Counters that update together</h1><MyButtoncount={count}onClick={handleClick}/><MyButtoncount={count}onClick={handleClick}/></div>);}functionMyButton({count,onClick}){return(<buttononClick={onClick}>      Clicked{count} times</button>);}

Next Steps

By now, you know the basics of how to write React code!

Check out theTutorial to put them into practice and build your first mini-app with React.



[8]ページ先頭

©2009-2025 Movatter.jp