0% found this document useful (0 votes)
9 views18 pages

React Development: Basics to Advanced Guide

This series teaches how to develop applications with JavaScript and React. The first part discusses the differences between JavaScript and ECMAScript and introduces basic React concepts such as components. The second part shows how to create a React project using Create React App and develop the first component.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

React Development: Basics to Advanced Guide

This series teaches how to develop applications with JavaScript and React. The first part discusses the differences between JavaScript and ECMAScript and introduces basic React concepts such as components. The second part shows how to create a React project using Create React App and develop the first component.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

React: from basic to advanced – Part 1

React is a JavaScript library for building user interfaces.

This is the first part of a series of articles that teaches how to develop and structure
aplicações comJavaScripteReact.

JavaScript vs. ECMAScript


ECMAScriptis the name of thestandardized version ofJavaScript, that is, it is the specification
used to develop JavaScript implementations.

We can say that ECMAScript is the recipe for creating implementations


JavaScript, such as Mozilla's SpiderMonkey, Google's V8, and Chakra
from Microsoft. It is these implementations that make it possible to run JavaScript on your
browser.

ECMAScript has several versions, the best known are 5.1, 2015 (formerly known
like 6), 2016 (previously known as 7) and 2017 (previously known as 8). Each new
The version brings new functionalities. No new version breaks the previous one.

In this series, we assume that you are familiar with ECMAScript up to version 5.1. Whenever
if we use a feature that was added after version 5.1, let's talk about it
in detail.

Don't worry if we use a feature that your preferred browser still


it didn't implement, it will work anyway without any effort on your part.

React vs. JavaScript

Image for illustrative purposes only, don't worry if you didn't understand.

JavaScript is a language and React is a library.


It is important to keep in mind that, when developing applications using React, the most
part of the time, you will be writing "pure" JavaScript, which is why the importance of
masterJavaScript.

This does not mean that to develop applications with React, you need to be a
master in JavaScript. It means that the more you know JavaScript, the better
your code will be simpler.

I like to say that I only really learned JavaScript when I met React, but this
It didn't happen overnight, I learned over time.

React vs. AngularJS vs. [Link]


I have used various JavaScript frameworks and libraries, such [Link], [Link],
AngularJS 1, [Link], among others.

I don't really agree with comparisons that attempt to find a winner among
technologies for app development.

The truth is that each library or framework has its advantages and disadvantages.
You need to decide which is the best, based on the needs of your application and team.
development, that is, each case is a case, and there is no library or framework
perfect for all cases.

Instead of comparing React with other libraries or frameworks, in the next parts
In this series, I will explain why React returns the structuring and development of apps.
easier and more fun and what are its best features.

React, Flux, Redux or MobX?

Merely illustrative image, do not worry if you did not understand.

React provides native solutions for communication between components:


Communication between components that have a parent-child relationship or of
son to father;
Communication between sibling components.

However, for communication between components that are far from each other, you need to create
your own state management system or use a ready-made solution, such as
Flux, Redux or MobX.

I have already used Flux, Redux, MobX and several other variants of Flux in my projects.
the verdict is that each library has advantages and disadvantages, there is no one solution
definitive for state management. The choice depends on the type of application that
you are developing and your team.

Unfortunately, I realize that several developers choose Redux only because


it is the most famous state management library, without even stopping to
think about whether the project really needs a library for management of
state.

Every library introduces an additional level of complexity to the project, you must
evaluate if you really need it and if there are already solutions within the libraries that
you already use.

For 90% of front-end projects that did not need to work offline, not even
I needed to use a library for state management, 'pure' React solved it.
my problem.

In the next parts of this series, I will talk about each management library.
state, including how to use only React for local state management and
global.

Summary
In this series, we will teach how to develop apps using JavaScript and React.

We assume that you are familiar with ECMAScript up to version 5.1 and whenever we use
a feature that was added after version 5.1, we will talk about it in detail.

We will not make comparisons with other libraries or frameworks. Instead,


let's focus on talking about the functionalities of React and how it solves the
problems we face in our daily lives.

We will also talk about routing, state management, and when to use one.
ready-made solution or create your own.
React: do básico ao avançado–Parte 2
React is a JavaScript library for building user interfaces.

This is the second part of a series of articles that teaches how to develop and structure
applications with JavaScript and React.

Click here if you have not read the first part yet.

I believe you are eager to create your first app using React. So
Let's go!

[Link] and npm

Before you start, make sure you have [Link](v4+) on your computer.

[Link]é utilizado para rodar programasJavaScriptno seu computador.

In the case of front-end applications created with React, we use [Link] only for
run, test and create a build for production of our project.

[Link] has a package manager callednpmNode Package Manager


it is automatically installed when you install [Link].

In this series, we will not talk much about [Link] npm, but we will explain what
Each command we use does.

Hello React!
Open a new tab or window in your command line and execute:

npm install -g create-react-app


create-react-app hello-react
cd hello-react
npm start

After that, you can open the URL [Link] in your preferred browser to
visualize your app.

If you want to change the source code, open the corresponding file, make the changes.
And hello. The URL [Link] will be updated automatically (as long as you
be running the commandnpm start).
Important: in addition to JavaScript files, you can import CSS files, images,
among others. We will talk about file imports in detail in the next ones
parts of this series.

When you are ready to put your app into production, just runnpm run
buildinstead ofnpm startA production version will be generated in the build folder.
just copy these files to your production server.

Just like that!

The first command we executed (npm install -g create-react-app ) installs and


a new command called is now availablecreate-react-app.

Create React App is a tool created and maintained by the creators of React. It is
used to create apps without the need to configure building tools
testingcomowebpack, Babel, Autoprefixer, ESLint, Jest, among others.

If you were afraid to learn React because you would need to learn a bunch of other things
tools, you can stay calm! Thanks to the team ofReactyou just need to worry
withJavaScriptReact.

In summary, Create React App does the 'dirty' work so that you don't have to worry about
tools for building and testing. You can focus only on development
from your app without having to worry about webpack, Babel, Autoprefixer, etc. Everything is
ready for you to use, without the need for prior setup.

The second command (create-react-app hello-react create a React project


pastahello-reactand install the necessary packages.

The third command navigates to the folderhello-react.

The fourth—and final—command makes access to the app available through the URL.
[Link]

Componentize everything!
Image taken from How we unit test React components using expect-jsx

The main idea of React is that you create components for absolutely everything and that
you avoid the imperative style and adopt the declarative style.

Later on, I will explain why componentization is interesting, what style is.
imperative and what is declarative style. For now, just remember that, with React,
you will be 100% of the time creating components that do only one thing, but
they do very well.

Our first component.


When we remember that, with React, we will be creating components that do only
One thing—and they do it very well—we will create our first component.

Open the [Link] the foldersourceof the projecthello-reactnewly created and replace
all existing source code for:

Snippet 1 – [Link]

advanced/blob/master/[Link]

After saving the file, if the URL [Link] is open, it will be


automatically updated and you will be able to see the result.

Phew! I made it. And now?


Se você chegou até aqui, muito bem! Você instalou [Link], rodou sua primeiraReact
appe created its first component.

You probably just copied and pasted the source code without really understanding what it is.
happening and is full of questions, perhaps even frustrated.
If this is your case, don't worry. This was expected. Instead of showing a 'Hello
World! Common, I wanted to show an example that encompasses practically everything you
will use in your day to day with React.

Seriously?! Is React just that?!?! There are many other features that we will see.
later, but this is practically everything you use in your daily life to create front-
end appscomReact.

Nesta série vamos falar profundamente sobre todas as funcionalidades doReact,routing


the state management, but you probably won't use all the features in the
day by day, and that is intentional. Less is more.

It is important to know all the functionalities of the technologies you use, however it is
wise to use only when really necessary and always prefer simple code
legible.

The secret to creating scalable apps is that they can grow without breaking functionalities.
already existing, is to write simple and readable code. This also allows for the inclusion or
exchange of developers without major pains.

The three types of developers


Just to complement, I believe there are three types of developers:

1. Beginner: has little or no mastery of the technology they are using.


and becomes extremely happy when something works.
2. Intermediate: masters the technology being used and writes code
complex, using advanced techniques or prematurely optimizing, likes
to show everyone that you wrote a code that almost no one understands
just to show that you have knowledge.
[Link]: has complete mastery over the technology they are using and writes
extremely simple and readable code so that even a beginner
understand. You know and master advanced techniques, but you only use them when
strictly necessary.

Summary
In this part of the series you installed [Link] and ran your first app with React.
You also learned that with React you create components for absolutely everything, and
that each component does just one thing, but it does it very well.

If you didn't understand anything or little of what theSnippet


1do it, no problem. The
the upcoming parts of this series will explain each concept in a detailed and easy way
understand.

React: from basic to advanced - Part 3


React is a JavaScript library for building user interfaces.

This is the third part of a series of articles that teaches how to develop and structure
applications with JavaScript and React.

Click here if you haven't read the second part yet.

I imagine you must be eager to write code, but first I want to explain
some concepts that will help understand what the code written with React really is
does.

What problem does React solve?


React was created to solve just one problem: developing small and medium apps.
or large ones, which have data that changes over time.

To achieve this goal, with React, you just need to describe how your app should look.
present at a certain moment based on the data received from the user,
browser back-end.

When some data changes, React simply 'presses' the refresh button and knows how.
update only the parts that changed, that is, the interface updates are
automatically managed for you.

É por isso que React incentiva você a escrever código declarativo em vez de imperativo.
Ao invés de dizercomo fazer, você dizo que quer, e o React faz o trabalho chato pra
you.
Hmm. I don't know if I understood...

Sure, I will illustrate the previous explanation with pseudocode.

Se você ainda não usou React, provavelmente você só trabalhou com classes e
instances. For example, with [Link], Can you create a componentButton
creating a class. When the app is running, instances of the componentButton
they will be created, each with its own properties.

In this traditional model, it is up to you to create, update, and destroy instances of


child components. If a componentFormdo you want to render aButton, he needs
create an instance of theButtonkeep the instance updated after receiving
new data and destroy it when no longer needed.

Following is a pseudo implementation of the componentForm:

class Form extends TraditionalView { render() { if (![Link] &&


if (![Link]) { // Form has not been submitted yet, // and an instance of
Button has not been created yet.

Let's create an instance of Button,


[Link] = new Button()

add it to this Form,


[Link]([Link])

// define some attributes,


[Link] = 'primary'
[Link] = [Link]

and finally, render the created instance.


[Link]()
}

if ([Link] && [Link]) {


// Form was submitted,
and an instance of Button has been created.

Let's remove the Button instance from this Form,


[Link]([Link])

and destroy it to clear the memory.


[Link]()
}

if ([Link] && ![Link]) {


// Form has been submitted,
and an instance of Message has not yet been created.

Let's create an instance of Message,


[Link] = new Message()

// add it to this Form,


[Link]([Link])

// define an attribute,
[Link] = 'Sucesso!'

and finally, render the created instance.


[Link]()
}

}
}

This is pseudocode and will not work.

As said, this is just pseudocode, but it's more or less what you write.
quando usa bibliotecas tradicionais como [Link].

In the traditional model, each instance of a component needs to maintain its reference.
noDOM, besides creating, updating, and destroying instances of child components. The code
grows absurdly if the parent component has several child components or
various types of state. Additionally, since parent components have direct access
At the request of the child components, it is extremely difficult to decouple them in the future.

How is React different?


In React, the concept of elements was created. An element is an object that describes
an instance and its properties. This instance can be a component, a tag
HTML or an SVG tag.

It is important to understand that, in fact, an element is not an instance, instead


That's just the way you tell React that you want to render something.
Therefore, elements do not have methods and are immutable.

Elements are, nothing more, nothing less, than objects with just two properties:
typeandprops.

Whentypeis a string, the element represents an HTML or SVG tag and its
attributes.

Here is an example:

const myAwesomeInput = { type: 'input', props: { type: 'text', value:


' ' } }
// myAwesomeInput represents the following HTML structure:
AAAA

This is a pseudocode and it will not work.

Note: if you are curious to find out what it is, watch this video.

In the example above,typedefine a tag HTML epropsyour attributes.

As elements, in fact, are just objects that describe an instance, they are
much lighter than true instances.

In addition to a string, you can pass a component that you created totype, and this,
it's the main idea of React.

Elements that describe a component created by you are like elements that
they describe an HTML or SVG tag. There is no difference. They can be nested and
combinations.

This feature allows you to create a component calledButtonwith a


propertycolorspecific, without worrying if theButtonwill render abutton,
umdivor anything else.

Here is an example of the definition and use of the componentButton:

function Button(props) {
return {
type: 'button',
props: {
style: {
color: [Link]
},
children: [Link] }
}
}

const myAwesomeButton = { type: Button, props: { color: 'blue',


children: ' ' } }

// myAwesomeButton represents the following HTML structure:


Button color="blue">AAAA</Button>

...that when rendered by React, will transform into:


ʀʀʀʀ

This is pseudocode and it will not work.

Did you notice that we used a property calledchildrenThis native property


React was created so that the parent element can receive one or more child elements.
It is through it that we can create element trees.

We will not go into details about the [Link], what matters is to have
keep in mind that in the previous example, we passed a string tochildren, and React knows
how to render it correctly. Instead of a string, we could also have
after one or more elements, we chose a string because we want to show a
basic text as content of theButton.

Now that we know how elements work, we can rewrite ourForm


using React and the concept of elements.

Here is a pseudo implementation:

function Form(props) {
if ([Link]) {
// Form has been submitted,
// vamos pedir para o React renderizar
an element of type Message
with a property
return { type: Message, props: { content: 'Sucesso!' }
}
}

// Form was not submitted,


let's ask React to render
// a Button type element
with some properties
return {
type: Button,
props: {
type: 'primary',
label: [Link]
}
}
}

This is pseudocode and it will not work.

As you can see, we delegate to React the creation, updating, and


destruction of instances. We only tell React declaratively what
we want, and he takes care of managing the instances.

Note: the explanations and examples were based on the [Link] Components
Elements, and Instances created by Dan Abramov.

Summary
In this part of the series, we learn what React solves and how it solves it.
React: from basic to advanced - Part 4
React is a JavaScript library for building user interfaces.

This is the fourth part of a series of articles that teaches how to develop and structure
applications with JavaScript and React.

Click here if you haven't read the third part yet.

In the previous section, we learned what React solves and how it solves it. In this part,
let's talk about the children property and how to create elements.

The children property


Every component has a type and, optionally, properties.

In addition to the properties that HTML tags have and the properties that we create for
In our custom components, there is a special property called children.

Here is an example:

const myAwesomeButton = {
type: 'button',
props: {
children: 'Submit'
}
}

// myAwesomeButton represents the following HTML structure:


Submit

As you can see in this example, children represents the HTML datag content
button, that is, everything you pass to children will be interpreted as the content
data HTML and React component:

const myAwesomeDangerButton = {
type: DangerButton,
props: {
children: 'Delete'
}
}

// myAwesomeDangerButton represents the following HTML structure:


<DangerButton>Delete</DangerButton>

In the example above, DangerButton is a component created by us, and its children are
Delete

The most interesting thing is that children functions like any other property, that is,
In addition to strings, you can pass numbers, booleans, objects, arrays, functions, and one or
but more elements (HTML tags or components).
Although you can pass any value for children, in daily life it is likely that you
only pass strings, elements, and functions.

Passar umafunctionparachildrené uma das funcionalidades mais poderosas do React.


Let's talk about her later.

By the way, the library I use in all my projects was created using the
functionality of passing a function to children. Let's talk about this library
Later, however, if you want to support a Brazilian project, leave your note.
GitHub Small dots.

Creating elements
[Link]() is the function used to create elements in React.

Until now, we were using objects to represent a React element and,


Indeed, this representation is correct, because in a summarized way,
[Link]() only returns an object with type and props for us.

However, to create elements in React you should always use the function
[Link](), in addition to a series of validations, it registers the element in
internal registration of React, so instances are managed automatically without
any work on our part.

There is no other way to create elements in React, the only available API is
[Link](), and this is great, because we have an extremely simple API!

Note: actually, there are two other ways to create elements, [Link]()
[Link].x()(x is the name of the tag you want to create. However, the use of these
functions have been discouraged by the team responsible for React and will probably be
deprecated in the near future. Therefore, we will not talk about them.

If you are already familiar with React, you could argue that we can also create
elements with JSX. This is true, however when JSX is compiled to JavaScript,
everything will be converted to calls to [Link]().

// With JSX, if you write:

<p id="apple">
Pineapple
</p>

This will be converted to:


[Link]('p', { id: 'apple' }, 'Pineapple')

Let's talk about JSX in the next part of this series.

Using [Link]()
Nasecond partIn this series, we learn to create React projects with the tool
Create React App. If you haven't installed it yet, read the second part.
again to carry out the installation.

Create a new project:

create-react-app superlab
cd superlab
npm start

superlab will be our testing laboratory.

Image taken from [Link]

After creating the project superlabfinalizar and running the command npm start, open the
filesrc/[Link].

Remove the following statement:

<p className="App-intro">
To get started, edit <code>src/[Link]</code> and save to reload.
</p>

Instead of creating this paragraph with JSX, let's use [Link]().

The official API is as follows:

[Link](type, [props], [...children])


The first argument is the type of element we want to create, that is, it can be a
HTML tag or a component that you created. Remember that HTML tags must be
past as string.

The second argument is optional and is an object containing all the properties that
Do you want to pass to the element.

Remember the special children property? You should not define it inside the second one.
argument props, and yes, in the third argument. The third argument is also
optional.

And the three dots? What does it mean?! Children is the plural of child, so children is
composed of one or more children, where each child can be a string, a number,
an element, etc.

That's why the three dots. It means that from the third argument you can
pass one or more child, thus forming children.

After removing the statement we discussed earlier, add in its place:

[Link]
p
{ className: App intro },
To get started, edit
[Link]('code', null, 'src/[Link]')
and save to reload.
)}

Note that in the first argument, we pass the type of element we want. Already in
second argument, we pass the properties of the element. In the third argument,
we pass a string as the first child. In the fourth argument, we pass a new
element as the second child, and in the fifth argument we pass a string as
thirdchild, that is, the third, fourth, and fifth arguments form children.

It is important to note that when you want to pass children, but the element does not have
no other property, you must pass null as the second argument. Remember
also that every child does not necessarily need to be an element,
it can be a string, a number, etc.

Important!

Don't forget the keys at the beginning and end, as src/[Link] is using JSX.
indicates that the compiler should start interpreting JavaScript instead of JSX. Let's go
talk about it in detail in the next part.

How to declare a reserved word in modern JavaScript, we must use


className to pass classes to elements in React.

Don't worry if you don't know what JS is or don't understand how it works. The next
part will be about JSX.
Now save the file and in your browsernavigate to [Link] If you do not
you typed nothing wrong, everything should work as expected.

Summary
We learned how the children property works and how we create elements in
React.

React: from basic to advanced – Part 5


React is a JavaScript library for building user interfaces.

This is the fifth part of a series of articles that teaches how to develop and structure
applications with JavaScript and React.

Click here if you haven't read the fourth part yet.

In the previous part, we learned how the children property works and how we create
elements in React. Now let's understand what JSX is.

What is JSX?
JSX is justsyntactic sugarIt is possible to write XML within code.
JavaScript.

XML?! Wouldn't it be HTML? No. JSX is also used on other platforms, for
example, for the development of iOS and Android apps.

On iOS you can render a datepicker like this:

<DatePickerIOS>
date="2016-12-31"
onDateChange={() => [Link](' ')}
/>

Cool, right? If all the articles reach more than 100 likes, I will extend the series and
talk about developing iOS and Android apps with React. If not, no.

JSX is totally optional, you don't have to use it if you don't want to. In the case of
app development with React, everything that JSX does, [Link]() does too
makes.
What do you mean, in the case of app development with React?! JSX wasn't made for
Does it only work with React? [Link] is a specificationand any preprocessor
JavaScript code can use the specification to transform JSX into anything.
useful.

JSX was not created to be implemented by JavaScript engines (SpiderMonkey, V8,


etc.) or browsers. It is also not a proposed functionality to be included in the
The [Link] specification is just a specification created so thatpre-
JavaScript processors transform XML syntax into plain JavaScript.

If you don't remember what ECMAScript is, read the first part of this series.

In the case of React, JSX is converted into calls to [Link](), however


Other projects can convert JSX into any JavaScript code they want.

To summarize, in React, JSX is used to create elements, that is, JSX is just
a more elegant alternative to [Link]().

Since we are using the tool in this seriesCreate React Appto create projects
React, you can write JSX normally and it will be converted to JavaScript without
any effort on your part.

If you do not want to use Create React App, you will need to set [Link]
your project. Babel is a JavaScript preprocessor, and we will not discuss it in this
series because we are using Create React App, which does all the setup
necessary from Babel for us.

You are probably wondering now if you should use JSX or not.

Unfortunately, I can't answer that for you, but I can help you make that decision. In
in the next article, I will explain how to use JSX and list some advantages and
disadvantages.

Summary
In this part, we learned what JSX is. In the next part of this series, we will...
to deepen your usage and functioning.

You might also like