Basics of React.Js
By: Nicky Liu
Tags: Software Engineering, Programming, Software Development, React, JavaScript

Once you know JavaScript, you can immediately cause changes in your browser by manipulating the DOM. You can use JavaScript or jQuery to add or remove elements or change values when things are clicked and create an interactive website. However, DOM manipulation requires some excessive steps. If you want to change a displayed number on a website with DOM manipulation, you need to manually reassign the value or text of that element to the new one. If you have a lot of elements that update on changing a single thing, then you need to manually reassign for all of them. But this is where React.js comes in!

Creating A React App

Create a react app.

npx create-react-app appName

cd appName npm start

A new page should open up with a spinning atom on it. This means your app is running.

Now open it up in the text editor of your choice. Open the src folder and the App.js file. This is the file mainly responsible for showing you the spinning atom page. Inside of the header the img tag is responsible for the atom, the p tag is responsible for the line of white text, and the ‘a’ tag is responsible for the blue link at the bottom.

Now delete the header. Your page should now only have the following code:

import React from 'react';

import logo from './logo.svg';

import './App.css'; function App() {

return (

<div className="App"> </div>

);

} export default App;

You will see a white page. Now let’s get started.

As you may have guessed from the sample template given, the display is very similar to basic HTML. The main difference is that everything is wrapped in divs.

Add some paragraph’s inside the div.

<div className="App">

<p>Paragraph Line</p>

<p>Paragraph Line</p>

<p>Paragraph Line</p>

</div>

Now on the page, you can see three-paragraph lines.

Instead of putting in the same line three times however, you can create a component that says the line, then just re-use that component.

Functional Component

Create a new file called Paragraph.js and enter the following text inside.

import React from "react"; const Paragraph = (props) => {

return(

<div>

<p>Paragraph Line</p>

</div>

)

} export default Paragraph;

This is called a functional component. It is just a function used for displaying information. It has no state or time hook (we will learn about these in a second).

In our original App.js file, import the Paragraph from the Paragraph.js file.

import Paragraph from './paragraph.js';

Instead, change the div to show:

return (

<div className="App">

<Paragraph />

<Paragraph />

<Paragraph />

</div>

);

Now you are displaying the Paragraph component three times, and it looks exactly the same as earlier.

The other type of component is called a class component. It has a life cycle meaning you can make it do things at certain times, such as when the component is first being displayed or about to be removed, and a state.

Class Component

Create a new file called Number.js.

import React from "react"; export default class Number extends React.Component { render() {

return(

<div>

<p>1</p>

<p>2</p>

<p>3</p>

</div>

)

}

}

Add our new number class component to our app.js file.

return (

<div className="App">

<Paragraph />

<Paragraph />

<Paragraph />

<Number />

</div>

);

State

To give it a state, add the following to it:

state = {

number: 0

}

This gives the state a number value that is currently set to 0.

Add a button that when clicked tells you information on the state.

import React from "react"; export default class Number extends React.Component { state = {

number: 0

} printNumber = () => {

console.log(this.state)

} render() {

return(

<div>

<p>1</p>

<p>2</p>

<p>3</p>

<button onClick={this.printNumber()}>Print State</button>

</div>

)

}

}

Firstly, you will see that your state is printed, but you can also make it print a specific variable in the state, in this case specifically the number variable.

Change the print number function to:

printNumber = () => {

console.log(this.state.number)

}

Now it will print the number inside of the state.

But you may now notice that the number is printed automatically without you clicking the button and that clicking the button actually doesn’t print anything in addition at all. This is because of the way the function is called inside of our button.

<button onClick={this.printNumber()}>Print State</button>

Right now, the function is being called the second the button is made. We want to make the button call the function on click.

<button onClick={() => {this.printNumber()}}>Print State</button>

The function now does just that.

You can also make it so the something is passed into the function when the button is clicked, such as button information if you want a few buttons to run the same function but with different values based on the button (such as a calculator) or when entering information inside of a form.

Change the button to:

<button id="button" onClick={(event) => {this.printNumber(event)}}>Print State</button>

Change the function to:

printNumber = (event) => {

console.log(this.state.number)

console.log(event)

console.log(event.target)

console.log(event.target.id)

}

Now when pressed, it will print state.number, the event that called it (a click), as well as the specific thing that called the even (the button). Like in state above, you can also access the specific attribute you want, such as id or class name, by doing event.target.attribute.

You can change state by the setState function.

this.setState({

number: this.state.number + 1

})

This will set the number inside of state to be one more than whatever it currently is.

Wrap it inside a function:

addOne = () => {

this.setState({

number: this.state.number + 1

})

console.log(this.state.number)

}

And add a new button:

<button id="button" onClick={(event) => {this.addOne(event)}}>Add Number</button>

If you click it multiple times, you see that it prints a number each time and that each number increases each time.

However, you will notice that each time it prints the old number first, then add one and that this process is repeated each time. It looks like the function is printing first then adding to the number inside of state, but it should be doing the opposite!

This is because setState takes a small amount of time, while console logging is instantaneous.

You can, however, set it so that the print happens explicitly after state is finished changing. Change the addOne function to:

addOne = () => {

this.setState({

number: this.state.number + 1

}, () => {

console.log(this.state.number)

})

}

Now it works as you would expect, the number is increased by 1 and the result is printed.

Lifecycle

You can make a component do things like run functions or change state at specific times.

Add a new function that sets the state to something weird.

funkyState = () => {

this.setState({

number: 999

})

}

We can make this function run as soon as the component is shown:

componentDidMount(){

this.funkyState()

}

Now if you refresh the page and hit the Print State button, you will see that the number inside of state was instantly set to 999.

Forms

Create a new file called Form.js.

import React from "react"; export default class Form extends React.Component { render() {

return(

<div>

<p>Hello, Name!</p>

<form>

Name: <input type="text" value='' />

<input type="submit" value="Submit" />

</form>

</div>

)

}

}

Add it to our app.js file.

return (

<div className="App">

<Paragraph />

<Paragraph />

<Paragraph />

<Number />

<Form />

</div>

);

This is a form where you can write your name, and submit it. We want to make it so that the “Hello, Name!” line shows the name that you submit in the name bar. The value of the name bar is set to an empty string so that it doesn’t display a value by default. However, this means that no matter what you type in, nothing will display. This is where state comes in.

Set up state.

state = {

name: '',

submittedName: ''

}

You can change the input line so that whenever it changes, it updates the name-value inside of state, and it updates its own value to reflect the name inside of state. Add a function to handle change and update the name input line.

handleChange = (event) => {

this.setState({

name: event.target.value

})

} Name: <input type="text" value={this.state.name} onChange={event => {this.handleChange(event)}} />

This makes it so whenever there is a change in the name box (such as when you are typing) it will call the handleChange function and pass in the typing changes you made, updating state.name. And since the value is now set to reflect state.name, whatever you type is also reflected inside of the bar.

Change the hello line above to:

<p>Hello, {this.state.submittedName}!</p>

Right now the submittedName is blank so nothing will show up. Add the following submit function and changes to the form.

submit = (event) => {

this.setState({

submittedName: this.state.name

})

} <form onSubmit={(event) => {this.submit(event)}}>

Now enter a name hit submit.

You see that your submitted name will be displayed for a fraction of a second before disappearing. This is because the page refreshes on a submit. You need to add the following line to the submit function:

event.preventDefault()

This stops the normal auto-refresh.

submit = (event) => {

this.setState({

submittedName: this.state.name

})

event.preventDefault()

}

Now enter a name and try it again, and it should work as you would expect!

Props

Information can be passed from one component to another in the form of props.

Create two new files called ‘sample1.js’ and ‘sample2.js’.

Inside of sample1 enter the following code:

import React from "react"; const Sample1 = (props) => {

return(

<div>

<p>Sample 1</p>

</div>

)

} export default Sample1;

This will be a functional component.

Import sample1 and add it to the bottom of the div:

<Sample1 />

The page will now display the line ‘Sample 1’.

If you want to pass props to it from the form component, you do by doing:

<Sample1 name={this.state.name} submittedName={this.state.submittedName}/>

When you use the imported component, you also add:

variableName={variableToPass}

The variable name can be anything, although it is best to make it consistent.

To access props inside a functional component do props.variableName, where variableName is the name given when passing it in.

Change the lines inside of sample1 to:

import React from "react"; const Sample1 = (props) => {

return(

<div>

<p>props.name</p>

<p>props.submittedName</p>

<p>{props.name}</p>

<p>{props.submittedName}</p>

</div>

)

} export default Sample1;

You will see that the first two lines just say the words “props.name” and “props.submittedName”. But the third and fourth lines are blank.

If you start typing into the bar, the third line will start reflecting whatever you are typing. This is because it shows whatever is inside the name variable that was passed down, which is the name inside of state of the first component. The second line shows submittedName, so it will only show a. value after you hit enter and actually set it to something.

Notice that the lines change by themselves without you having to manually assign new values or anything to them, unlike if you were using regular HTML/DOM manipulation. Through the use of props and state, things automatically change to match the state whenever there are changes to the state.

To access props inside a class component is slightly different, you use this.props.variableName, where variableName is the name given when passing it in.

Change the lines inside of sample2 to:

import React from "react"; export default class Sample2 extends React.Component { render() {

return(

<div>

<p>this.props.name</p>

<p>this.props.submittedName</p>

<p>{this.props.name}</p>

<p>{this.props.submittedName}</p>

</div>

)

}

}

Everything else is basically the same.

CSS

Inside your folder, you will see that you already came with an ‘App.css’ file. Inside your App.js file you will see that the file is already imported at the top via the line:

import './App.css';

This means any changes to that CSS file will be applied globally.

CSS is pretty standard, with the exception that the ‘class’ attribute is instead called ‘className’.

If you go back to ‘App.js’ you will notice that the original div was given the className “App”. If you change is to ‘class1’ and add the following inside of the CSS file:

.class1 {

color: blue

}

You will see that now everything is no longer centered and that all of the text is blue. This is because the earlier formatting was for members of the ‘app’ class.

Miscellaneous

If you want to run a function or get the value of a variable inside of a normal line similar to the way you would normally use ${} for a string, here you use curly braces.

Add the following function to the top:

numberFunction = () => {

return (9 + 9)

}

Open up ‘Number.js’ again add the following two lines to the bottom:

<p>5 + 5</p>

<p>{5 + 5}</p>

<p>{this.numberFunction()}</p>

The first line will just display the line ‘5 + 5’ but the second will actually display 10. The last line similar displays 18, which is the return value of the numberFunction.

Congratulations, you now know the basics of React.js! A useful addition to React is Redux, which you can find the basics of in my other article on Redux: https://medium.com/future-vision/redux-in-react-7f1776f2443d. Have fun making frontend applications with your new-found knowledge!