How to React to a Proposal You Know Is Coming
React is one of the most pop JavaScript frameworks ever created, and I believe that it'south i of the best tools out there.
The goal of this handbook is to provide a starter guide to learning React.
At the finish of the book, you lot'll have a bones agreement of:
- What React is and why it'south so popular
- How to install React
- React Components
- React Country
- React Props
- Handling user events in React
- Lifecycle events in a React component
These topics volition be the base upon which yous volition build in other more advanced React tutorials.
This book is especially written for JavaScript programmers who are new to React. So allow's go started.
What is React?
React is a JavaScript library that aims to simplify the development of visual interfaces.
Adult at Facebook and released to the earth in 2013, information technology drives some of the most widely used apps, powering Facebook and Instagram amid endless other applications.
Its primary goal is to brand it piece of cake to reason about an interface and its land at any bespeak in fourth dimension. Information technology does this past dividing the UI into a collection of components.
You might experience some initial difficulties when learning React. But once information technology "clicks", I guarantee information technology's going to be one of the best experiences you lot ever accept. React makes many things easier, and its ecosystem is filled with bully libraries and tools.
React in itself has a very modest API, and you basically need to understand 4 concepts to get started:
- Components
- JSX
- State
- Props
We'll explore all of these in this book, and we'll leave the more avant-garde concepts to other tutorials. I volition requite you some pointers in the last section most how to movement forward.
And you can download this handbook in PDF / ePub / Mobi format for complimentary.
Summary of the handbook
- How much JavaScript you need to know to use React
- Why should you learn React?
- How to install React
- React Components
- Introduction to JSX
- Using JSX to compose a UI
- The deviation betwixt JSX and HTML
- Embedding JavaScript in JSX
- Managing state in React
- Component Props in React
- Data flow in a React application
- Handling user events in React
- Lifecycle events in a React component
- Where to get from here
How much JavaScript you need to know to utilise React
Before jumping straight into React, you should take a good agreement of some core JavaScript concepts.
Y'all don't have to exist a JavaScript proficient, but I recall you need a good overview of:
- Variables
- Arrow functions
- Work with objects and arrays using Balance and Spread
- Object and array destructuring
- Template literals
- Callbacks
- ES Modules
If those concepts audio unfamiliar, I've provided you lot with some links to find out more most those subjects.
Why should y'all learn React?
I highly recommend that any Spider web developer has at least a basic understanding of React.
That'due south because of a few reasons.
- React is very popular. As a developer, information technology'south quite likely that you lot're going to work on a React project in the future. Perhaps an existing project, or mayhap your team will desire you lot to work on a brand new app based on React.
- A lot of tooling today is congenital using React at the core. Popular frameworks and tools like Next.js, Gatsby, and many others utilise React nether the hood.
- Every bit a frontend engineer, React is probably going to come in a job interview.
Those are all skillful reasons, simply one of the main reasons I want you to larn React is that it's neat.
It promotes several proficient development practices, including lawmaking reusability and component-driven evolution. It is fast, it is lightweight, and the mode it makes you recall about the data menstruum in your application perfectly suits a lot of common scenarios.
How to install React
There are a few different means to install React.
To start with, I highly recommend one approach, and that's using the officially recommended tool chosen create-react-app.
create-react-app is a control line awarding, aimed at getting you upward to speed with React in no time.
Yous first by using npx, which is an like shooting fish in a barrel way to download and execute Node.js commands without installing them.
Encounter my npx guide here: https://flaviocopes.com/npx/
npx comes with npm (since version five.2). If you lot don't have npm installed already, do it now from https://nodejs.org (npm is installed with Node).
If you are unsure which version of npm you have, run npm -five to check if y'all need to update.
Tip: cheque out my OSX last tutorial at https://flaviocopes.com/macos-final/ if y'all're unfamiliar with using the concluding. Information technology applies to Mac and Linux.
When y'all run npx create-react-app <app-name>, npx is going to download the most contempo create-react-app release, run it, and then remove it from your system.
This is dandy because you lot volition never have an outdated version on your organization, and every fourth dimension you run it, you lot're getting the latest and greatest code available.
Let's start so:
npx create-react-app todolist
This is when it finished running:
create-react-app created a file construction in the folder you told it to (todolist in this instance), and initialized a Git repository.
It likewise added a few commands in the package.json file:
So yous tin can immediately offset the app by going into the newly created application folder and running npm first.
Past default this command launches the app on your local port 3000, and it opens your browser showing you the welcome screen:
At present you're fix to work on this application!
React Components
In the last department yous saw how to create your first React awarding.
This application comes with a serial of files that practice various things, mostly related to configuration, only there's one file that stands out: App.js.
App.js is the first React Component you meet.
Its code is this:
import React from 'react' import logo from './logo.svg' import './App.css' office App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ) } export default App An application built using React, or one of the other popular frontend frameworks like Vue and Svelte for example, is built using dozens of components.
Simply let's start past analyzing this kickoff component. I'1000 going to simplify this component code like this:
import React from 'react' import logo from './logo.svg' import './App.css' role App() { return /* something */ } consign default App Y'all can run across a few things here. We import some things, and we export a part called App.
The things we import in this example are a JavaScript library (the react npm package), an SVG paradigm, and a CSS file.
create-react-appis gear up in a way that allows u.s. to import images and CSS to use in our JavaScript, but this is non something you demand to care about now. What you demand to care about is the concept of a component
App is a function that, in the original case, returns something that at first sight looks quite strange.
Information technology looks similar HTML but it has some JavaScript embedded into information technology.
That is JSX, a special language nosotros use to build a component's output. We'll talk more about JSX in the next section.
In addition to defining some JSX to return, a component has several other characteristics.
A component can take its own state, which ways it encapsulates some variables that other components can't access unless this component exposes this state to the balance of the application.
A component tin also receive data from other components. In this instance nosotros're talking about props.
Don't worry, we're going to await in detail at all those terms (JSX, State and Props) shortly.
Introduction to JSX
We can't talk about React without get-go explaining JSX.
In the final section yous met your first React component, the App component divers in the default application built past create-react-app.
Its code was this:
import React from 'react' import logo from './logo.svg' import './App.css' function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</lawmaking> and salve to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ) } export default App We previously ignored everything that was inside the render statement, merely in this section we're going to talk about it.
We telephone call JSX everything wrapped inside the parentheses returned by the component:
<div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and relieve to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> This looks like HTML, but it's not really HTML. It's a little different.
And it'due south a bit strange to have this code inside a JavaScript file. This does not expect like JavaScript at all!
Nether the hood, React will process the JSX and information technology will transform it into JavaScript that the browser volition exist able to translate.
So nosotros're writing JSX, merely in the end at that place's a translation step that makes it digestible to a JavaScript interpreter.
React gives us this interface for 1 reason: it's easier to build UI interfaces using JSX.
One time y'all become more than familiar with it, of course.
In the next department nosotros'll talk almost how JSX lets you lot easily compose a UI, so we'll look at the differences with "normal HTML" that y'all need to know.
Using JSX to etch a UI
Equally introduced in the last section, i of the master benefits of JSX is that it makes it very like shooting fish in a barrel to build a UI.
In particular, in a React component you tin import other React components, and you can embed them and brandish them.
A React component is usually created in its ain file, because that'southward how we can easily reuse it (past importing it) in other components.
Simply a React component can also be created in the aforementioned file of another component, if you plan to only utilise it in that component. There's no "rule" here, you tin can exercise what feels all-time to you.
I generally apply split files when the number of lines in a file grows likewise much.
To keep things simple let's create a component in the same App.js file.
We're going to create a WelcomeMessage component:
part WelcomeMessage() { return <p>Welcome!</p> } Encounter? It's a simple function that returns a line of JSX that represents a p HTML element.
Nosotros're going to add it to the App.js file.
At present inside the App component JSX we tin add <WelcomeMessage /> to show this component in the user interface:
import React from 'react' import logo from './logo.svg' import './App.css' function WelcomeMessage() { return <p>Welcome!</p> } role App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <WelcomeMessage /> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ) } export default App And hither'southward the event. Can yous see the "Welcome!" message in the screen?
We say that WelcomeMessage is a child component of App, and App is its parent componnet.
We're adding the <WelcomeMessage /> component as if it was part of the HTML language.
That's the beauty of React components and JSX: nosotros can compose an awarding interface and use information technology similar nosotros're writing HTML.
With some differences, as we'll see in the next section.
The difference betwixt JSX and HTML
JSX kind of looks like HTML, but it's not.
In this section I want to introduce yous to some of the virtually important things y'all demand to continue in mind when using JSX.
I of the differences might be quite obvious if yous looked at the App component JSX: there's a foreign attribute called className.
In HTML nosotros utilize the class attribute. It's probably the most widely used attribute, for various reasons. 1 of those reasons is CSS. The class attribute allows us to style HTML elements easily, and CSS frameworks like Tailwind put this attribute to the centre of the CSS user interface pattern process.
Just at that place'south a problem. Nosotros are writing this UI lawmaking in a JavaScript file, and form in the JavaScript programming language is a reserved word. This ways nosotros can't apply this reserved discussion equally we want. It serves a specific purpose (defining JavaScript classes) and the React creators had to choose a unlike name for it.
That's how we ended up with className instead of class.
You demand to remember this peculiarly when you're copy/pasting some existing HTML.
React will try its best to make sure things don't pause, but it will heighten a lot of warnings in the Developer Tools:
This is non the only HTML feature that suffers from this trouble, but it's the nigh common i.
Another big departure between JSX and HTML is that HTML is very relaxed, we tin say. Even if yous take an mistake in the syntax, or you close the wrong tag, or you have a mismatch, the browser volition effort its best to translate the HTML without breaking.
It's one of the core features of the Spider web. Information technology is very forgiving.
JSX is not forgiving. If you lot forget to close a tag, you volition have a articulate error message:
React usually gives very practiced and informative mistake messages that bespeak yous in the right direction to set up the problem.
Another large departure between JSX and HTML is that in JSX we tin embed JavaScript.
Let's talk about this in the next department.
Embedding JavaScript in JSX
1 of the best features of React is that nosotros can easily embed JavaScript into JSX.
Other frontend frameworks, for case Angular and Vue, take their own specific ways to print JavaScript values in the template, or perform things like loops.
React doesn't add new things. Instead, information technology lets us utilise JavaScript in the JSX, by using curly brackets.
The first example of this that I will show you lot comes straight from the App component we've studied so far.
We import the logo SVG file using
import logo from './logo.svg' and and so in the JSX nosotros assign this SVG file to the src attribute of an img tag:
<img src={logo} className="App-logo" alt="logo" /> Let'due south do another instance. Suppose the App component has a variable called message:
function App() { const message = 'Hello!' //... } We can print this value in the JSX by calculation {message} anywhere in the JSX.
Inside the curly brackets { } nosotros tin add any JavaScript statement, but just ane statement for every curly subclass block.
And the argument must render something.
For instance this is a common statement you lot will find in JSX. We accept a ternary operator where we ascertain a condition (message === 'Hullo!'), and we print one value if the status is true, or another value (the content of message in this case) if the condition is false:
{ message === 'Hello!' ? 'The bulletin was "Howdy!"' : message } Managing land in React
Every React component tin can accept its ain country.
What practice we hateful past state? The state is the ready of information that is managed by the component.
Think virtually a form, for example. Each individual input element of the form is responsible for managing its state: what is written within it.
A button is responsible for knowing if information technology'southward being clicked, or not. If it's on focus.
A link is responsible for knowing if the mouse is hovering over information technology.
In React, or in any other components-based framework/library, all our applications are based on and make heavy apply of components' state.
Nosotros manage state using the useState utility provided past React. It'south technically a claw (you don't need to know the details of hooks right at present, just that's what it is).
You import useState from React in this way:
import React, { useState } from 'react' Calling useState(), y'all will get back a new state variable, and a office that nosotros can call to alter its value.
useState() accepts the initial value of the state item and returns an assortment containing the state variable, and the function you telephone call to change the country.
Example:
const [count, setCount] = useState(0) This is of import. We can't just change the value of a state variable directly. We must telephone call its modifier function. Otherwise the React component will not update its UI to reflect the changes of the data.
Calling the modifier is the style nosotros can tell React that the component state has changed.
The syntax is a scrap weird, right? Since useState() returns an array we use assortment destructuring to access each individual item, like this: const [count, setCount] = useState(0)
Here's a practical example:
import { useState } from 'react' const Counter = () => { const [count, setCount] = useState(0) return ( <div> <p>You clicked {count} times</p> <push button onClick={() => setCount(count + 1)}>Click me</button> </div> ) } ReactDOM.render(<Counter />, certificate.getElementById('app')) You tin can add as many useState() calls as you want, to create as many state variables as you lot want:
const [count, setCount] = useState(0) const [anotherCounter, setAnotherCounter] = useState(0) Component Props in React
Nosotros call props the initial values passed to a component.
Nosotros previously created a WelcomeMessage component
office WelcomeMessage() { render <p>Welcome!</p> } and nosotros used it like this:
<WelcomeMessage /> This component does non have whatever initial value. It does not accept props.
Props tin exist passed equally attributes to the component in the JSX:
<WelcomeMessage myprop={'somevalue'} /> and inside the component we receive the props as arguments:
function WelcomeMessage(props) { render <p>Welcome!</p> } It's common to employ object destructuring to go the props past name:
function WelcomeMessage({ myprop }) { return <p>Welcome!</p> } Now that we have the prop, we can use it inside the component. For example we tin can impress its value in the JSX:
function WelcomeMessage({ myprop }) { return <p>{myprop}</p> } Curly brackets here take various meanings. In the case of the office argument, curly brackets are used every bit part of the object destructuring syntax.
Then we use them to ascertain the function code cake, and finally in the JSX to print the JavaScript value.
Passing props to components is a great way to pass values around in your application.
A component either holds data (has state) or receives data through its props.
We can also send functions equally props, so a kid component can call a office in the parent component.
A special prop is called children. That contains the value of anything that is passed between the opening and closing tags of the component, for instance:
<WelcomeMessage> Here is some bulletin </WelcomeMessage> In this case, inside WelcomeMessage nosotros could access the value Here is some message by using the children prop:
function WelcomeMessage({ children }) { return <p>{children}</p> } Data flow in a React application
In a React application, data typically flows from a parent component to a child component, using props as nosotros saw in the previous section:
<WelcomeMessage myprop={'somevalue'} /> If you pass a office to the child component, you tin can withal modify the state of the parent component from a child component:
const [count, setCount] = useState(0) <Counter setCount={setCount} /> Within the Counter component we can now take hold of the setCount prop and call it to update the count state in the parent component, when something happens:
function Counter({ setCount }) { //... setCount(1) //... } Y'all need to know that there are more than advanced ways to manage data, which include the Context API and libraries like Redux. But those introduce more complexity, and xc% of the times using those 2 ways I only explained are the perfect solution.
Handling user events in React
React provides an piece of cake fashion to manage events fired from DOM events similar clicks, form events, and more than.
Permit's talk about click events, which are pretty simple to digest.
You tin apply the onClick aspect on any JSX element:
<button onClick={(event) => { /* handle the event */ }} > Click here </push> When the element is clicked, the part passed to the onClick aspect is fired.
Y'all tin can ascertain this office exterior of the JSX:
const handleClickEvent = (result) => { /* handle the outcome */ } role App() { return <button onClick={handleClickEvent}>Click here</push button> } When the click event is fired on the button, React calls the event handler function.
React supports a vast amount of types of events, similar onKeyUp, onFocus,onChange, onMouseDown, onSubmit and many more.
Lifecycle events in a React component
So far we've seen how to manage state with the useState hook.
There's another hook I desire to innovate in this volume: useEffect.
The useEffect claw allows components to have admission to the lifecycle events of a component.
When yous call the claw, you laissez passer it a function. The function will exist run by React when the component is first rendered, and on every subsequent re-render/update.
React start updates the DOM, then calls any function passed to useEffect().
All without blocking the UI rendering, even on blocking code.
Here is an example:
const { useEffect, useState } = React const CounterWithNameAndSideEffect = () => { const [count, setCount] = useState(0) useEffect(() => { console.log(`You clicked ${count} times`) }) return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ) } Since the useEffect() role is run on every subsequent re-return/update of the component, nosotros can tell React to skip it, for performance purposes. Nosotros exercise this by adding a 2d parameter which is an assortment that contains a list of state variables to watch for.
React will only re-run the side issue if i of the items in this array changes.
useEffect(() => { panel.log(`Hi ${name} y'all clicked ${count} times`) }, [name, count]) Similarly, y'all can tell React to only execute the side effect once (at mount time), by passing an empty array:
useEffect(() => { console.log(`Component mounted`) }, []) You migth observe yourself using this selection a lot.
useEffect() is great for adding logs, accessing tertiary party APIs, and much more.
Where to go from here
Mastering the topics explained in this article is a great step towards your goal of learning React.
I want to requite you some pointers at present, because it's like shooting fish in a barrel to get lost in the sea of tutorials and courses well-nigh React.
What should you lot learn side by side?
Learn more theory most the Virtual DOM, writing declarative code, unidirectional data flow, immutability, limerick.
Start building some simple React applications. For instance build a elementary counter or a collaborate with a public API.
Acquire how to perform provisional rendering, how to perform loops in JSX, how to use the React Programmer Tools.
Acquire how to apply CSS in a React application, with plain CSS or Styled Components.
Learn how to manage state using the Context API, useContext and Redux.
Learn how to interact with forms.
Acquire how to use React Router.
Learn how to test React applications.
Learn an application framework built on meridian of React, like Gatsby or Next.js.
About of all, make sure you practice past building sample applications to apply everything you've learned.
Conclusion
Thanks a lot for reading this handbook.
I hope it will inspire you to larn more virtually React and everything you tin do with it!
Call back that yous can download this handbook in PDF / ePub / Mobi format for free if yous desire.
I publish programming tutorials every day on my website flaviocopes.com if you want to bank check out more great content like this.
You can reach me on Twitter @flaviocopes.
Larn to lawmaking for free. freeCodeCamp'due south open source curriculum has helped more than 40,000 people go jobs as developers. Get started
Source: https://www.freecodecamp.org/news/react-beginner-handbook/
0 Response to "How to React to a Proposal You Know Is Coming"
Post a Comment