0% found this document useful (0 votes)
11 views52 pages

Create Your First React JS Project

The document provides a comprehensive guide on building a React JS project, covering essential concepts such as ES6 features, JSX, components, props, and state management. It explains how to create and render components, handle props, and manage component lifecycle methods. Additionally, it includes code examples to illustrate the implementation of these concepts in a React application.

Uploaded by

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

Create Your First React JS Project

The document provides a comprehensive guide on building a React JS project, covering essential concepts such as ES6 features, JSX, components, props, and state management. It explains how to create and render components, handle props, and manage component lifecycle methods. Additionally, it includes code examples to illustrate the implementation of these concepts in a React application.

Uploaded by

satyendradrive
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Build first React JS project

npm uninstall -g create-react-app

npm install -g create-react-app

npx create-react-app myfirstreact

cd .\myfirstreact

npm start
What is ES6?
ES6 stands for ECMAScript 6.

Why Should I Learn ES6?


React uses ES6, and you should be familiar with some of the new features like:

 Classes
 Arrow Functions

 Variables (let, const, var)

To create a class inheritance, use the extends keyword.

The super() method refers to the parent class.

Arrow Functions
Arrow functions were introduced in ES6.

Before:
hello = function() {
return "Hello World!";
}

With Arrow Function:


hello = () => {
return "Hello World!";
}

Arrow Functions Return Value by Default:


hello = () => "Hello World!";

Arrow Function With Parameters:


hello = (val) => "Hello " + val;
Arrow Function Without Parentheses:
hello = val => "Hello " + val;

What About this?


In regular functions the this keyword represented the object that called the
function, which could be the window, the document, a button or whatever. this
represents object of caller.

With arrow functions, this keyword always represents the object (of class) that
defined the arrow function.

Example
With a regular function, this represents the object that called the function:

class Header {
constructor() {
[Link] = "Red";
}

//Regular function:
changeColor = function() {
[Link]("demo").innerHTML += this;
}
}

myheader = new Header();

//The window object calls the function:


[Link]("load", [Link]);

//A button object calls the function:


[Link]("btn").addEventListener("click",
[Link]);

Output
Regular Function

The this keyword represents different objects depending on how the function was called.

Click Me!

this represents:

[object Window][object HTMLButtonElement]

See the difference before and after the button is clicked.

Example
With an arrow function, this represents the Header object no matter who called
the function:

class Header {
constructor() {
[Link] = "Red";
}

//Arrow function:
changeColor = () => {
[Link]("demo").innerHTML += this;
}
}

myheader = new Header();

//The window object calls the function:


[Link]("load", [Link]);
//A button object calls the function:
[Link]("btn").addEventListener("click",
[Link]);

Output
Arrow Function

The this keyword represents the Header object.

Click Me!

this represents:

[object Object][object Object][object Object][object Object]

Variables
Now, with ES6, there are three ways of defining your variables: var, let,
and const. const is a variable that once it has been created, its value can
never change.

var has a function scope, not a block scope.

let has a block scope.

const has a block scope.

React Render HTML


React's goal is in many ways to render HTML in a web page.

React renders HTML to the web page by using a function


called [Link]().

The [Link]() function takes two arguments, HTML code and an


HTML element.

The purpose of the function is to display the specified HTML code inside the
specified HTML element.

The HTML Code


The HTML code in this tutorial uses JSX which allows you to write HTML tags
inside the JavaScript code:

Example
Create a variable that contains HTML code and display it in the root node:

const myelement = (
<table>
<tr>
<th>Name</th>
</tr>
<tr>
<td>John</td>
</tr>
<tr>
<td>Elsa</td>
</tr>
</table>
);

[Link](myelement, [Link]('root'));

React JSX
What is JSX?
JSX stands for JavaScript XML.

JSX allows us to write HTML in React.

JSX makes it easier to write and add HTML in React.

Coding JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM
without any createElement() and/or appendChild() methods.

JSX converts HTML tags into react elements.

JSX is an extension of the JavaScript language based on ES6, and is translated


into regular JavaScript at runtime.

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:

Example
Execute the expression 5 + 5:

const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

Inserting a Large Block of HTML


To write HTML on multiple lines, put the HTML inside parentheses:
Example
Create a list with three list items:

const myelement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);

One Top Level Element


The HTML code must be wrapped in ONE top level element.

So if you like to write two headers, you must put them inside a parent element,
like a div element

Example
Wrap two headers inside one DIV element:

const myelement = (
<div>
<h1>I am a Header.</h1>
<h1>I am a Header too.</h1>
</div>
);
JSX will throw an error if the HTML is not correct, or if the HTML misses a parent
element.

React Components
Components are like functions that return HTML elements.
Components are independent and reusable bits of code. They serve the same
purpose as JavaScript functions, but work in isolation and returns HTML via a
render function.

Components come in two types, Class components and Function components, in


this tutorial we will concentrate on Class components.

Create a Class Component


When creating a React component, the component's name must start with an
upper case letter.

The component has to include the extends [Link] statement, this


statement creates an inheritance to [Link], and gives your
component access to [Link]'s functions.

The component also requires a render() method, this method returns HTML.

Example
Create a Class component called Car

class Car extends [Link] {


render() {
return <h2>Hi, I am a Car!</h2>;
}
}

Now your React application has a component called Car, which returns
a <h2> element.

To use this component in your application, use similar syntax as normal


HTML: <Car />

Example
Display the Car component in the "root" element:

[Link](<Car />, [Link]('root'));


Create a Function Component
A Function component also returns HTML, and behaves pretty much the same
way as a Class component, but Class components have some additions, and will
be preferred in this tutorial.

Example
Create a Function component called Car

function Car() {
return <h2>Hi, I am also a Car!</h2>;
}

Once again your React application has a Car component.

Refer to the Car component as normal HTML (except in React,


components must start with an upper case letter):

Example
Display the Car component in the "root" element:

[Link](<Car />, [Link]('root'));

Component Constructor
If there is a constructor() function in your component, this function will be
called when the component gets initiated.

The constructor function is where you initiate the component's properties.

In React, component properties should be kept in an object called state.

You will learn more about state later in this tutorial.


State (Get Out of Component)
The constructor function is also where you honor the inheritance of the parent
component by including the super() statement, which executes the parent
component's constructor function, and your component has access to all the
functions of the parent component ([Link]).

Example
Create a constructor function in the Car component, and add a color property:

class Car extends [Link] {


constructor() {
super();
[Link] = {color: "red"};
}
render() {
return <h2>I am a Car!</h2>;
}
}

Use the color property in the render() function:

Example
class Car extends [Link] {
constructor() {
super();
[Link] = {color: "red"};
}
render() {
return <h2>I am a {[Link]} Car!</h2>;
}
}

Props (Set into Component)


Another way of handling component properties is by using props.

Props are like function arguments, and you send them into the component as
attributes.

You will learn more about props in the next chapter.

Example
Use an attribute to pass a color to the Car component, and use it in the render()
function:

class Car extends [Link] {


render() {
return <h2>I am a {[Link]} Car!</h2>;
}
}

[Link](<Car color="red"/>,
[Link]('root'));

Components in Components
We can refer to components inside other components:

Example
Use the Car component inside the Garage component:

class Car extends [Link] {


render() {
return <h2>I am a Car!</h2>;
}
}

class Garage extends [Link] {


render() {
return (
<div>
<h1>Who lives in my Garage?</h1>
<Car />
</div>
);
}
}

[Link](<Garage />, [Link]('root'));

Components in Files
React is all about re-using code, and it can be smart to insert some of your
components in separate files.

To do that, create a new file with a .js file extension and put the code inside it:

Note that the file must start by importing React (as before), and it has to end
with the statement export default Car;.

Example
This is the new file, we named it "[Link]":

import React from 'react';


import ReactDOM from 'react-dom';

class Car extends [Link] {


render() {
return <h2>Hi, I am a Car!</h2>;

}
}

export default Car;

To be able to use the Car component, you have to import the file in your
application.

Example
Now we import the "[Link]" file in the application, and we can use the Car
component as if it was created here.

import React from 'react';


import ReactDOM from 'react-dom';
import Car from './[Link]';

[Link](<Car />, [Link]('root'));

React Props

Props are arguments passed into React components.

Props are passed to components via HTML attributes.

React Props are like function arguments in JavaScript and attributes in HTML.

Example
Add a "brand" attribute to the Car element:

const myelement = <Car brand="Ford" />;


The component receives the argument as a props object:

Example
Use the brand attribute in the component:

class Car extends [Link] {


render() {
return <h2>I am a {[Link]}!</h1>;
}
}

If you have a variable to send, and not a string as in the example above, you
just put the variable name inside curly brackets:

Example
Create a variable named "carname" and send it to the Car component:

class Car extends [Link] {


render() {
return <h2>I am a {[Link]}!</h2>;
}
}

class Garage extends [Link] {


render() {
const carname = "Ford";
return (
<div>
<h1>Who lives in my garage?</h1>
<Car brand={carname} />
</div>
);
}
}

[Link](<Garage />, [Link]('root'));

Or if it was an object:

Example
Create an object named "carinfo" and send it to the Car component:

class Car extends [Link] {


render() {
return <h2>I am a {[Link]}!</h2>;
}
}

class Garage extends [Link] {


render() {
const carinfo = {name: "Ford", model: "Mustang"};
return (
<div>
<h1>Who lives in my garage?</h1>
<Car brand={carinfo} />
</div>
);
}
}

[Link](<Garage />, [Link]('root'));


Props in the Constructor
If your component has a constructor function, the props should always be
passed to the constructor and also to the [Link] via
the super() method.

Example
class Car extends [Link] {
constructor(props) {
super(props);
}
render() {
return <h2>I am a Car!</h2>;
}
}

[Link](<Car model="Mustang"/>,
[Link]('root'));

React State

React components has a built-in state object.

The state object is where you store property values that belongs to the
component.

When the state object changes, the component re-renders.

Creating the state Object


The state object is initialized in the constructor:
Example:
Specifiy the state object in the constructor method:

class Car extends [Link] {


constructor(props) {
super(props);
[Link] = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}

The state object can contain as many properties as you like:

Example:
Specify all the properties your component need:

class Car extends [Link] {


constructor(props) {
super(props);
[Link] = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}

Using the state Object


Refer to the state object anywhere in the component by using
the [Link] syntax:

Example:
Refer to the state object in the render() method:

class Car extends [Link] {


constructor(props) {
super(props);
[Link] = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My {[Link]}</h1>
<p>
It is a {[Link]}
{[Link]}
from {[Link]}.
</p>
</div>
);
}
}

Changing the state Object


To change a value in the state object, use the [Link]() method.

When a value in the state object changes, the component will re-render,
meaning that the output will change according to the new value(s).

Example:
Add a button with an onClick event that will change the color property:

class Car extends [Link] {


constructor(props) {
super(props);
[Link] = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
[Link]({color: "blue"});
}
render() {
return (
<div>
<h1>My {[Link]}</h1>
<p>
It is a {[Link]}
{[Link]}
from {[Link]}.
</p>
<button
type="button"
onClick={[Link]}
>Change color</button>
</div>
);
}
}
Always use the setState() method to change the state object, it will ensure
that the component knows its been updated and calls the render() method (and
all the other lifecycle methods).

React Lifecycle

Lifecycle of Components
Each component in React has a lifecycle which you can monitor and manipulate
during its three main phases.

The three phases are: Mounting, Updating, and Unmounting.

Mounting
Mounting means putting elements into the DOM.

React has four built-in methods that gets called, in this order, when mounting a
component:

1. constructor()

The constructor() method is called before anything else, when the


component is initiated, and it is the natural place to set up the
initial state and other initial values.
The constructor() method is called with the props, as arguments, and
you should always start by calling the super(props) before anything
else, this will initiate the parent's constructor method and allows the
component to inherit methods from its parent ([Link]).

class Header extends [Link] {


constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}

[Link](<Header />, [Link]('root'));

2. getDerivedStateFromProps()

The getDerivedStateFromProps() method is called right before


rendering the element(s) in the DOM.

This is the natural place to set the state object based on the
initial props.

It takes state as an argument, and returns an object with changes to


the state.

class Header extends [Link] {


constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: [Link] };
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}

[Link](<Header favcol="yellow"/>,
[Link]('root'));

3. render()

The render() method is required, and is the method that actual outputs
HTML to the DOM.

class Header extends [Link] {


render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}

[Link](<Header />, [Link]('root'));

4. componentDidMount()

The componentDidMount() method is called after the component is


rendered.

This is where you run statements that requires that the component is
already placed in the DOM.

class Header extends [Link] {


constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}

[Link](<Header />, [Link]('root'));

Updating
The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the


component's state or props.

React has five built-in methods that gets called, in this order, when a component
is updated:

1. getDerivedStateFromProps()

Also at updates the getDerivedStateFromProps method is called. This is


the first method that is called when a component gets updated.

2. shouldComponentUpdate()

In the shouldComponentUpdate() method you can return a Boolean


value that specifies whether React should continue with the rendering or
not.
The default value is true.

3. render()
4. getSnapshotBeforeUpdate()

In the getSnapshotBeforeUpdate() method you have access to


the props and state before the update, meaning that even after the
update, you can check what the values were before the update.

If the getSnapshotBeforeUpdate() method is present, you should also


include the componentDidUpdate() method, otherwise you will get an
error.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and after
one second, the favorite color becomes "yellow".

This action triggers the update phase, and since this component has
a getSnapshotBeforeUpdate() method, this method is executed, and writes a
message to the empty DIV1 element.

Then the componentDidUpdate() method is executed and writes a message in


the empty DIV2 element:

Example:
Use the getSnapshotBeforeUpdate() method to find out what
the state object looked like before the update:

class Header extends [Link] {


constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
[Link]("div1").innerHTML =
"Before the update, the favorite was " +
[Link];
}
componentDidUpdate() {
[Link]("div2").innerHTML =
"The updated favorite is " + [Link];
}
render() {
return (
<div>
<h1>My Favorite Color is {[Link]}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}

[Link](<Header />, [Link]('root'));

5. componentDidUpdate()

The componentDidUpdate method is called after the component is


updated in the DOM.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color


"red".

When the component has been mounted, a timer changes the state, and
the color becomes "yellow".
This action triggers the update phase, and since this component has
a componentDidUpdate method, this method is executed and writes a
message in the empty DIV element:

Example:
The componentDidUpdate method is called after the update has been
rendered in the DOM:

class Header extends [Link] {


constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
componentDidUpdate() {
[Link]("mydiv").innerHTML =
"The updated favorite is " + [Link];
}
render() {
return (
<div>
<h1>My Favorite Color is {[Link]}</h1>
<div id="mydiv"></div>
</div>
);
}
}

[Link](<Header />, [Link]('root'));


Unmounting
The next phase in the lifecycle is when a component is removed from the DOM,
or unmounting as React likes to call it.

React has only one built-in method that gets called when a component is
unmounted:

 componentWillUnmount()

The componentWillUnmount method is called when the component is about to


be removed from the DOM.

Example:
Click the button to delete the header:

class Container extends [Link] {


constructor(props) {
super(props);
[Link] = {show: true};
}
delHeader = () => {
[Link]({show: false});
}
render() {
let myheader;
if ([Link]) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={[Link]}>Delete
Header</button>
</div>
);
}
}

class Child extends [Link] {


componentWillUnmount() {
alert("The component named Header is about to be
unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}

[Link](<Container />,
[Link]('root'));

React Events

Just like HTML, React can perform actions based on user events.

React has the same events as HTML: click, change, mouseover etc.

Adding Events
React events are written in camelCase syntax:

onClick instead of onclick.

React event handlers are written inside curly braces:

onClick={shoot} instead of onClick="shoot()".


Event Handlers
A good practice is to put the event handler as a method in the component class:

Example:
Put the shoot function inside the Football component:

class Football extends [Link] {


shoot() {
alert("Great Shot!");
}
render() {
return (
<button onClick={[Link]}>Take the shot!</button>
);
}
}

[Link](<Football />, [Link]('root'));

Bind this
For methods in React, the this keyword should represent the component that
owns the method.

That is why you should use arrow functions. With arrow functions, this will
always represent the object that defined the arrow function.

Example:
class Football extends [Link] {
shoot = () => {
alert(this);
/*
The 'this' keyword refers to the component object
*/
}
render() {
return (
<button onClick={[Link]}>Take the shot!</button>
);
}
}

[Link](<Football />, [Link]('root'));

Why Arrow Functions?


In class components, the this keyword is not defined by default, so with regular
functions the this keyword represents the object that called the method, which
can be the global window object, a HTML button, or whatever.

Read more about binding this in our React ES6 'What About this?' chapter.

If you must use regular functions instead of arrow functions you have to
bind this to the component instance using the bind() method:

Example:
Make this available in the shoot function by binding it in
the constructor function:

class Football extends [Link] {


constructor(props) {
super(props)
[Link] = [Link](this)
}
shoot() {
alert(this);
/*
Thanks to the binding in the constructor function,
the 'this' keyword now refers to the component object
*/
}
render() {
return (
<button onClick={[Link]}>Take the shot!</button>
);
}
}

[Link](<Football />, [Link]('root'));

Passing Arguments
If you want to send parameters into an event handler, you have two options:

class Football extends [Link] {


shoot= (a)=>{
alert(a);
}
render() {
return (
<button onClick={()=>[Link]("Hi")}>Take the shot!</button>
);
}
}

[Link](<Football />, [Link]('root'));

React Event Object


Event handlers have access to the React event that triggered the function.

In our example the event is the "click" event. Notice that once again the syntax
is different when using arrow functions or not.
With the arrow function you have to send the event argument manually:

<button onClick={(ev) => [Link]("Goal", ev)}>Take the


shot!</button>

Without arrow function, the React event object is sent automatically as the last
argument when using the bind() method:

<button onClick={[Link](this, "Goal")}>Take the


shot!</button>

class Football extends [Link] {


shoot = (a, b) => {
alert(a);
alert([Link]);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}
render() {
return (
<button onClick={(evn) => [Link]("Goal", evn)}>Take the shot!
</button>
// <button onClick={[Link](this, "Goal")}>Take the shot!
</button> // this line and above line both works same
);
}
}

[Link](<Football />, [Link]('root'));

React Forms

Handling Forms
Handling forms is about how you handle the data when it changes value or gets
submitted.
In HTML, form data is usually handled by the DOM.

In React, form data is usually handled by the components.

When the data is handled by the components, all the data is stored in the
component state.

You can control changes by adding event handlers in the onChange attribute:

Example:
Add an event handler in the onChange attribute, and let the event handler
update the state object:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = { username: '' };
}
myChangeHandler = (event) => {
[Link]({username: [Link]});
}
render() {
return (
<form>
<h1>Hello {[Link]}</h1>
<p>Enter your name:</p>
<input
type='text'
onChange={[Link]}
/>
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));


Note: You must initialize the state in the constructor method before you can
use it.

Note: You get access to the field value by using


the [Link] syntax.

Conditional Rendering
If you do not want to display the h1 element until the user has done any input,
you can add an if statement.

Look at the example below and note the following:

1. We create an empty variable, in this example we call it header.

2. We add an if statement to insert content to the header variable if the user


has done any input.

3. We insert the header variable in the output, using curly brackets.

Example:
Display the header only if username is defined:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = { username: '' };
}
myChangeHandler = (event) => {
[Link]({username: [Link]});
}
render() {
let header = '';
if ([Link]) {
header = <h1>Hello {[Link]}</h1>;
} else {
header = '';
}
return (
<form>
{header}
<p>Enter your name:</p>
<input
type='text'
onChange={[Link]}
/>
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));

Submitting Forms
You can control the submit action by adding an event handler in the onSubmit
attribute:

Example:
Add a submit button and an event handler in the onSubmit attribute:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = { username: '' };
}
mySubmitHandler = (event) => {
[Link]();
alert("You are submitting " + [Link]);
}
myChangeHandler = (event) => {
[Link]({username: [Link]});
}
render() {
return (
<form onSubmit={[Link]}>
<h1>Hello {[Link]}</h1>
<p>Enter your name, and submit:</p>
<input
type='text'
onChange={[Link]}
/>
<input
type='submit'
/>
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));


Note that we use [Link]() to prevent the form from actually
being submitted.

Multiple Input Fields


You can control the values of more than one input field by adding
a name attribute to each element.

When you initialize the state in the constructor, use the field names.

To access the fields in the event handler use


the [Link] and [Link] syntax.

To update the state in the [Link] method, use square brackets


[bracket notation] around the property name.
Example:
Write a form with two input fields:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = {
username: '',
age: null,
};
}
myChangeHandler = (event) => {
let nam = [Link];
let val = [Link];
[Link]({[nam]: val});
}
render() {
return (
<form>
<h1>Hello {[Link]} {[Link]}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={[Link]}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={[Link]}
/>
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));

Note: We use the same event handler function for both input fields, we could
write one event handler for each, but this gives us much cleaner code and is the
preferred way in React.

Validating Form Input


You can validate form input when the user is typing or you can wait until the
form gets submitted.

Example:
When you fill in your age, you will get an alert if the age field is not numeric:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = {
username: '',
age: null,
};
}
myChangeHandler = (event) => {
let nam = [Link];
let val = [Link];
if (nam === "age") {
if (!Number(val)) {
alert("Your age must be a number");
}
}
[Link]({[nam]: val});
}
render() {
return (
<form>
<h1>Hello {[Link]} {[Link]}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={[Link]}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={[Link]}
/>
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));


Below you will see the same example as above, but the validation is done when
the form gets submitted instead of when you write in the field.

Example:
Same example, but with the validation at form submit:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = {
username: '',
age: null,
};
}
mySubmitHandler = (event) => {
[Link]();
let age = [Link];
if (!Number(age)) {
alert("Your age must be a number");
}
}
myChangeHandler = (event) => {
let nam = [Link];
let val = [Link];
[Link]({[nam]: val});
}
render() {
return (
<form onSubmit={[Link]}>
<h1>Hello {[Link]} {[Link]}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={[Link]}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={[Link]}
/>
<br/>
<br/>
<input type='submit' />
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));

Adding Error Message


Error messages in alert boxes can be annoying, so let's make an error message
that is empty by default, but displays the error when the user inputs anything
invalid:

Example:
When you fill in your age as not numeric, an error message is displayed:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = {
username: '',
age: null,
errormessage: ''
};
}
myChangeHandler = (event) => {
let nam = [Link];
let val = [Link];
let err = '';
if (nam === "age") {
if (val !="" && !Number(val)) {
err = <strong>Your age must be a number</strong>;
}
}
[Link]({errormessage: err});
[Link]({[nam]: val});
}
render() {
return (
<form>
<h1>Hello {[Link]} {[Link]}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={[Link]}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={[Link]}
/>
{[Link]}
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));


Textarea
The textarea element in React is slightly different from ordinary HTML.

In HTML the value of a textarea was the text between the start
tag <textarea> and the end tag </textarea>, in React the value of a textarea
is placed in a value attribute:

Example:
A simple textarea with some content initialized in the constructor:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = {
description: 'The content of a textarea goes in the value
attribute'
};
}
render() {
return (
<form>
<textarea value={[Link]} />
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));

Select
A drop down list, or a select box, in React is also a bit different from HTML.
in HTML, the selected value in the drop down list was defined with
the selected attribute:

HTML:
<select>
<option value="Ford">Ford</option>
<option value="Volvo" selected>Volvo</option>
<option value="Fiat">Fiat</option>
</select>

In React, the selected value is defined with a value attribute on the select tag:

Example:
A simple select box, where the selected value "Volvo" is initialized in the
constructor:

class MyForm extends [Link] {


constructor(props) {
super(props);
[Link] = {
mycar: 'Volvo'
};
}
render() {
return (
<form>
<select value={[Link]}>
<option value="Ford">Ford</option>
<option value="Volvo">Volvo</option>
<option value="Fiat">Fiat</option>
</select>
</form>
);
}
}

[Link](<MyForm />, [Link]('root'));

Styling React Using CSS

Inline Styling
To style an element with the inline style attribute, the value must be a
JavaScript object:

Example:
Insert an object with the styling information:

class MyHeader extends [Link] {


render() {
return (
<div>
<h1 style={{color: "red"}}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
Note: In JSX, JavaScript expressions are written inside curly braces, and since
JavaScript objects also use curly braces, the styling in the example above is
written inside two sets of curly braces {{}}.

camelCased Property Names


Since the inline CSS is written in a JavaScript object, properties with two names,
like background-color, must be written with camel case syntax:
Example:
Use backgroundColor instead of background-color:

class MyHeader extends [Link] {


render() {
return (
<div>
<h1 style={{backgroundColor: "lightblue"}}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}

JavaScript Object
You can also create an object with styling information, and refer to it in the style
attribute:

Example:
Create a style object named mystyle:

class MyHeader extends [Link] {


render() {
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Arial"
};
return (
<div>
<h1 style={mystyle}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}

CSS Stylesheet
You can write your CSS styling in a separate file, just save the file with
the .css file extension, and import it in your application.

[Link]:
Create a new file called "[Link]" and insert some CSS code in it:

body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Arial;
text-align: center;
}

Import the stylesheet in your application:

[Link]:
import React from 'react';
import ReactDOM from 'react-dom';
import './[Link]';

class MyHeader extends [Link] {


render() {
return (
<div>
<h1>Hello Style!</h1>
<p>Add a little style!.</p>
</div>
);
}
}

[Link](<MyHeader />, [Link]('root'));

CSS Modules
Another way of adding styles to your application is to use CSS Modules.

CSS Modules are convenient for components that are placed in separate files.

The CSS inside a module is available only for the component that imported it,
and you do not have to worry about name conflicts.

Create the CSS module with the .[Link] extension,


example: [Link].

[Link]:
Create a new file called "[Link]" and insert some CSS code in it:

.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Arial;
text-align: center;
}

Import the stylesheet in your component:

[Link]:
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './[Link]';

class Car extends [Link] {


render() {
return <h1 className={[Link]}>Hello Car!</h1>;
}
}

export default Car;

Import the component in your application:

[Link]:
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './[Link]';

[Link](<Car />, [Link]('root'));

React Sass

What is Sass
Sass is a CSS pre-processor.

Sass files are executed on the server and sends CSS to the browser.

You can learn more about Sass in our Sass Tutorial.


Can I use Sass?
If you use the create-react-app in your project, you can easily install and use
Sass in your React projects.

Install Sass by running this command in your terminal:

C:\Users\Your Name>npm install node-sass

Now you are ready to include Sass files in your project!

Create a Sass file


Create a Sass file the same way as you create CSS files, but Sass files have the
file extension .scss

In Sass files you can use variables and other Sass functions:

[Link]:
Create a variable to define the color of the text:

$myColor: red;

h1 {
color: $myColor;
}

Import the Sass file the same way as you imported a CSS file:

[Link]:
import React from 'react';
import ReactDOM from 'react-dom';
import './[Link]';
class MyHeader extends [Link] {
render() {
return (
<div>
<h1>Hello Style!</h1>
<p>Add a little style!.</p>
</div>
);

}
}

[Link](<MyHeader />, [Link]('root'));

You might also like