[go: up one dir, main page]

0% found this document useful (0 votes)
10 views12 pages

Reacts Js

The document provides a comprehensive overview of setting up a React application, including the necessary libraries and JSX syntax for creating components. It explains how to manage state using the useState hook and demonstrates building a StarRating component that allows users to rate content. Additionally, it covers best practices such as using className instead of class and object destructuring for props.

Uploaded by

cragnolinitomas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

Reacts Js

The document provides a comprehensive overview of setting up a React application, including the necessary libraries and JSX syntax for creating components. It explains how to manage state using the useState hook and demonstrates building a StarRating component that allows users to rate content. Additionally, it covers best practices such as using className instead of class and object destructuring for props.

Uploaded by

cragnolinitomas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

react js

Page Setup
In order to work with React in the browser, we need to include two libraries: React
and ReactDOM. React is the library for creating views. ReactDOM is the library used
to actually render the UI in the browser. Both libraries are available as scripts from
the unpkg CDN (links are included in the following code). Let’s set up an HTML
document:

React Elements
HTML is simply a set of instructions that a browser follows when constructing the
DOM. The elements that make up an HTML document become DOM elements
when the browser loads HTML and renders the user interface.
Let’s say you have to construct an HTML hierarchy for a recipe. A possible solution
for such a task might look something like this:
{

React with JSX

In JSX, an element’s type is specified with


a tag. The tag’s attributes represent the properties. The element’s children can be
added between the opening and closing tags.
It looks very similar to HTML:

<ul>
<li>1 lb Salmon</li>
<li>1 cup Pine Nuts</li>
<li>2 cups Butter Lettuce</li>
<li>1 Yellow Squash</li>
<li>1/2 cup Olive Oil</li>
<li>3 Cloves of Garlic</li>
</ul>

JSX Tips
JSX might look familiar, and most of the rules result in syntax that’s similar to HTML.
However, there are a few considerations you should understand when working with
JSX.
When we pass the array of ingredients to this component, we need to surround it
with curly braces. This is called a JavaScript expression, and we must use these when
passing JavaScript values to components as properties. Component properties will
take two types: either a string or a JavaScript expression. JavaScript expressions can
include arrays, objects, and even functions. In order to include them, you must sur‐
round them in curly braces.

Expressions in JSX
With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid


JavaScript expression. JSX will execute the expression and return the result:

const myElement = <h1>React is {5 + 5} times better with


JSX</h1>;

Nested components

JSX allows you to add components as children of other components. For example,
inside the IngredientsList, we can render another component called Ingredient
multiple times:

className

Since class is a reserved word in JavaScript, className is used to define the class
attribute instead:

JavaScript expressions

JavaScript expressions are wrapped in curly braces and indicate where variables will
be evaluated and their resulting values returned. For example, if we want to display
the value of the title property in an element, we can insert that value using a Java‐
Script expression. The variable will be evaluated and its value returned:

Recipes as JSX
The data is expressed in an array of two JavaScript objects. Each object contains the
name of the recipe, a list of the ingredients required, and a list of steps necessary to
cook the recipe.
We can create a UI for these recipes with two components: a Menu component for list‐
ing the recipes and a Recipe component that describes the UI for each recipe. It’s the
Menu component that we’ll render to the DOM. We’ll pass our data to the Menu com‐
ponent as a property called recipes:

The data is expressed in an array of two JavaScript objects. Each object contains the
name of the recipe, a list of the ingredients required, and a list of steps necessary to
cook the recipe.

We can create a UI for these recipes with two components: a Menu component for list‐
ing the recipes and a Recipe component that describes the UI for each recipe. It’s the
Menu component that we’ll render to the DOM. We’ll pass our data to the Menu com‐
ponent as a property called recipes:

The React elements within the Menu component are expressed as JSX. Everything is
contained within an article element. A header element, an h1 element, and a
div.recipes element are used to describe the DOM for our menu. The value for the
title property will be displayed as text within the h1:
Inside of the div.recipes element, we add a component for each recipe:

In order to list the recipes within the div.recipes element, we use curly braces to
add a JavaScript expression that will return an array of children. We can use the map
function on the props.recipes array to return a component for each object within
the array. As mentioned previously, each recipe contains a name, some ingredients,
and cooking instructions (steps). We’ll need to pass this data to each Recipe as props.
Also remember that we should use the key property to uniquely identify each
element.

You could also refactor this to use spread syntax. The JSX spread operator works like
the object spread operator. It will add each field of the recipe object as a property of
the Recipe component. The syntax here will supply all properties to the component:

Remember that this shortcut will provide all the properties to the Recipe component.
This could be a good thing but might also add too many properties to the component.
Another place we can make a syntax improvement to our Menu component is where
we take in the props argument. We can use object destructuring to scope the variables
to this function. This allows us to access the title and recipes variables directly, no
longer having to prefix them with props:
Now let’s code the component for each individual recipe:

Each recipe has a string for the name, an array of objects for ingredients, and an array
of strings for the steps. Using object destructuring, we can tell this component to
locally scope those fields by name so we can access them directly without having to
use props.name, props.ingredients, or props.steps.
The first JavaScript expression we see is being used to set the id attribute for the root
section element. It’s converting the recipe’s name to a lowercase string and globally
replacing spaces with dashes. The result is that “Baked Salmon” will be converted to
“baked-salmon” (and likewise, if we had a recipe with the name “Boston Baked
Beans,” it would be converted to “boston-baked-beans”) before it’s used as the id
attribute in our UI. The value for name is also being displayed in an h1 as a text node.

Inside of the unordered list, a JavaScript expression is mapping each ingredient to an


li element that displays the name of the ingredient. Within our instructions section,
we see the same pattern being used to return a paragraph element where each step is
displayed. These map functions are returning arrays of child elements.

Create React App

A pretty amazing tool to have at your disposal as a React developer is Create React
App, a command-line tool that autogenerates a React project.
To get started with Create React App, install the package globally:

npm install -g create-react-app

Then, use the command and the name of the folder where you’d like the app to be
created:

create-react-app my-project

Building a Star Rating Component

We would all be eating terrible food and watching terrible movies without the five-
star rating system.

The StarRating component will allow users to rate content based on a specific num‐
ber of stars. Content that’s no good gets one star. Highly recommended content gets
five stars. Users can set the rating for specific content by clicking on a specific star.
First, we’ll need a star, and we can get one from react-icons:

npm i react-icons

react-icons is an npm library that contains hundreds of SVG icons that are dis‐
tributed as React components. By installing it, we just installed several popular icon
libraries that contain hundreds of common SVG icons. You can browse all the icons
in the library. We’re going to use the star icon from the Font Awesome collection:
Here, we’ve created a StarRating component that renders five SVG stars that we’ve
imported from react-icons. The first three stars are filled in with red,and the last
two are grey.

A selected star should be filled in with red, and a star that’s


not selected should be greyed out. Let’s create a component that automatically files
the stars based upon the selected property:

The Star component renders an individual star and uses the selected property to fill
it with the appropriate color.

The 5-star rating system is pretty popular, but a 10-star rating system is far more
detailed. We should allow developers to select the total number of stars they wish to
use when they add this component to their app. This can be accomplished by adding
a totalStars property to the StarRating component:

All we have to do is supply the length of the array that we want to create and we get a new
array at that length. We use this function with the totalStars property to create an array of a
specific length. Once we have an array, we can map over it and render Star components.
By default, totalStars is equal to 5, which means this component will render 5 grey
stars, as shown in Figure 6-2.

The useState Hook

Since the rating is a value that will change, we’ll store and change
that value using React state. We incorporate state into a function component using a
React feature called Hooks.
Hooks contain reusable code logic that is separate from the
component tree.

we simply need to import it:

We’ll create a state variable called selectedStars, which will hold the user’s rating. We’ll
create this variable by adding the useState hook directly to the StarRating component:

We just hooked this component up with state. The useState hook is a function that
we can invoke to return an array. The first value of that array is the state variable we
want to use. In this case, that variable is selectedStars, or the number of stars the
StarRating will color red. useState returns an array. We can take advantage of array
destructuring, which allows us to name our state variable whatever we like. The value
we send to the useState function is the default value for the state variable. In this
case, selectedStars will initially be set to 3, as shown in Figure 6-3.

In order to collect a different rating from the user, we’ll need to allow them to click on
any of our stars. This means we’ll need to make the stars clickable by adding an
onClick handler to the FaStar component:

const Star = ({ selected = false, onSelect = f => f }) => (


<FaStar color={selected ? "red" : "grey"} onClick={onSelect} />
);

Here, we modified the star to contain an onSelect property. Check it out: this prop‐
erty is a function. When a user clicks on the FaStar component, we’ll invoke this
function, which can notify its parent that a star has been clicked. The default value for
this function is f => f. This is simply a fake function that does nothing; it just
returns whatever argument was sent to it. However, if we do not set a default function
and the onSelect property is not defined, an error will occur when we click the FaS
tar component because the value for onSelect must be a function. Even though f =>
f does nothing, it is a function, which means it can be invoked without causing
errors. If an onSelect property is not defined, no problem. React will simply invoke
the fake function and nothing will happen.

Now that our Star component is clickable, we’ll use it to change the state of the Star
Rating:

In order to change the state of the StarRating component, we’ll need a function that
can modify the value of selectedStars. The second item in the array that’s returned
by the useState hook is a function that can be used to change the state value. Again,
by destructuring this array, we can name that function whatever we like. In this case,
we’re calling it setSelectedStars, because that’s what it does: it sets the value of
selectedStars.
The most important thing to remember about Hooks is that they can cause the com‐
ponent they’re hooked into to rerender. Every time we invoke the setSelectedStars
function to change the value of selectedStars, the StarRating function component
will be reinvoked by the hook, and it will render again, this time with a new value for
selectedStars. This is why Hooks are such a killer feature. When data within the
hook changes, they have the power to rerender the component they’re hooked into
with new data.
The StarRating component will be rerendered every time a user clicks a Star. When
the user clicks the Star, the onSelect property of that star is invoked. When the onSe
lect property is invoked, we’ll invoke the setSelectedStars function and send it the
number of the star that was just selected. We can use the i variable from the map func‐
tion to help us calculate that number. When the map function renders the first Star,
the value for i is 0. This means that we need to add 1 to this value to get the correct
number of stars. When setSelectedStars is invoked, the StarRating component is
invoked with a the value for selectedStars, as shown in Figure 6-4.

You might also like