Learning ReactJS: Classes and Functions

If you are new to ReactJS then I would advice you to read my ReactJS Hello World article first and then proceed ahead. If you have some experience with ReactJS and want to explore Classes, Functions, Props, and State then you are in the right place, my friend.

Creating our React application and Initial clean up:

First, we will create our react application using create-react-app hello-world command and then delete logo.svg from our src directory and favicon.ico, logo192.png, logo512.png as they are no longer required. Once this is done following will be our directory structure:

+-- README.md 
+-- package-lock.json
+-- package.json
+-- node_modules
+-- .gitignore
+-- public
|   +-- index.html
|   +-- manifest.json
|   +-- robots.txt
+-- src
|   +-- App.css
|   +-- App.test.js
|   +-- index.js
|   +-- serviceWorker.js
|   +-- App.js
|   +-- index.css
|   +-- setupTests.js

Open the index.html file from the public directory and comment the following line from the code:

<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

Remove all the code from App.css file from the src directory and copy-paste the following code:

.App {
  text-align: center;
}

Now Remove all the code from the App.js file from the src directory and copy-paste the following code:

import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">
        Hello World
    </div>
  );
}

export default App;

Remember: Code under return() component is called as jsx. We will learn more about jsx in upcoming tutorials.

Let us run our application using the command npm start. You will see the following output:

React Hello world

Understanding Functions:

Functions in React are used to develop UI components without states. Wherever there is no need for maintaining a state object. You can use the Function.

Understanding classes:

Classes in React are used to develop UI components with states. Wherever there is a need for maintaining a state object. You can use classes.

We will discuss more regarding state objects in the next section of this tutorial.

Using props to pass values from one component to another:

Whenever you want to pass a value from one function to another you can use props to pass the value.

Let us create a new folder under the src directory named as components. Inside components directory, we will create a filename HelloUser.js.

+-- src
|   +-- components
|   +-- +-- HelloUser.js
|   +-- App.css
|   +-- App.test.js
|   +-- index.js
|   +-- serviceWorker.js
|   +-- App.js
|   +-- index.css
|   +-- setupTests.js

Now inside our App.js, we will call the HelloUser component. To call the HelloUser component we will use the syntax <HelloUser /> and import the HelloUser component into the App.js. We will pass the userName from our App.js to the HelloUser component.

App.js:

import React from 'react';
import HelloUser from './components/HelloUser'
import './App.css';


function App() {
  return (
    <div className="App">
      <HelloUser userName="Sharvin Shah"/>
    </div>
  );
}

export default App;

Go to the HelloUser under the components directory and we will get the value using the props.userName.

HelloUser.js:

import React from 'react'

function HelloUser(props) {
    return (
        <div>
            {props.userName}
        </div>
    )
}

export default HelloUser

Go to the browser and you will see the value Sharvin Shah that we have passed from the App.js to HelloUser.js using props is displayed.

React Props Pass

To pass the value from a function to a class you need to use this.props.userName instead of props.userName.

Understanding State:

Consider you want to build a form for your application. How can you achieve this? Well for such a situation we can use state. State in react are use to hold the data which we can display in our UI.

Let’s build a form for our application. Create a UserForm.js under the src/components directory. We will also import the UserForm component inside App.js and declare it in our jsx.

App.js:

import React from 'react';
import UserForm from './components/UserForm';
import './App.css';


function App() {
  return (
    <div className="App">
      <UserForm />
    </div>
  );
}

export default App;

Let’s write our traditional HTML form code under the jsx element inside the components/UserForm.js.

UserForm.js:

import React, { Component } from 'react'

class UserForm extends Component {
    render() {
        return (
            <div>
                <form>
                    <br /><br />
                    <input type="text" name="UserName" placeholder="User Name"/> 
                    <br /><br />
                    <input type="text" name="UserMessage" placeholder="Message"/>  
                    <br /><br />
                    <button>Submit</button>
                </form>
            </div>
        )
    }
}

export default UserForm

Now we will use the state to listen to the value from our form and hold the data so when the user presses the button to submit we can pass the information.

For this, we will use onChange and create a new arrow function named changeHandler and pass this to the onChange. We are using the Arrow function because react needs to bind the function inside the class. We will discuss more regarding binding in react in further tutorials. For time being just remember this reason for the use of arrow function here.

changeHandler accepts an event. Inside the event, you will find a lot of information but right now we are only interested in the information that is passed inside the form. This information is available inside the event.target.value.

In our changeHandler we will just console log whatever we type inside our form.

UserForm.js:

changeHandler = (event) => {
    console.log(event.target.value)
}

render() {
    return (
        <div>
            <form>
                <br /><br />
                <input type="text" name="UserName" placeholder="User Name" onChange={this.changeHandler}/> 
                <br /><br />
                <input type="text" name="UserMessage" placeholder="Message" onChange={this.changeHandler}/>  
                <br /><br />
                <button>Submit</button>
            </form>
        </div>
    )
}

Now we will create a constructor where we will initialize the state here with userName and userMessage.

The constructor is generally used for the initializing of the state object in ReactJS. We will discuss more regarding the constructor in the upcoming tutorials.

UserForm.js:

    constructor(props) {
        super(props)
    
        this.state = {
            UserName:"",
            UserMessage: ""
        }
    }

This is our final code after making all the changes:

UserForm.js:

import React, { Component } from 'react'

class UserForm extends Component {

    constructor(props) {
        super(props)
    
        this.state = {
            UserName:"",
            UserMessage: ""
        }
    }
    
    changeHandler = (event) => {
        console.log(event.target.value)
    }

    render() {
        return (
            <div>
                <form>
                    <br /><br />
                    <input type="text" name="UserName" placeholder="User Name" onChange={this.changeHandler}/> 
                    <br /><br />
                    <input type="text" name="UserMessage" placeholder="Message" onChange={this.changeHandler}/>  
                    <br /><br />
                    <button>Submit</button>
                </form>
            </div>
        )
    }
}

export default UserForm

Now run the application and go the browser and open the console using command/ctrl + options/alt + i. Go to the Console tab and inside our form type something and you will find that is printed in our console.

React State

Now we will use setState to set the value inside our state that we are passing in the form. Inside our form code, we have given a name parameter. This parameter holds a unique value for all the input tag. We will set the state of each input tag with the help of this name which is found inside the event.target.

UserForm.js:

changeHandler = (event) => {
    this.setState({
        [event.target.name]: event.target.value,
    })
}

We will add a new handleSubmit Handler which will read the data from the state when the submit button has been pressed. Inside this arrow function we will only log the value. In upcoming tutorials, we will pass the value to the backend server.

We will use event.preventDefault(); to automatically refresh the page when clicked on the submit button.

UserForm.js:

handleSubmit = (event) => {
    event.preventDefault();
    console.log(this.state);
}

render() {
    return (
        <div>
            <form>
                <br /><br />
                <input type="text" name="UserName" placeholder="User Name" onChange={this.changeHandler}/> 
                <br /><br />
                <input type="text" name="UserMessage" placeholder="Message" onChange={this.changeHandler}/>  
                <br /><br />
                <button onClick={this.handleSubmit}>Submit</button>
            </form>
        </div>
    )
}

We are done with our awesome form implementation. You can check out your code with the final code down below:

UserForm.js:

import React, { Component } from 'react'

class UserForm extends Component {

    constructor(props) {
        super(props)
    
        this.state = {
            UserName:"",
            UserMessage: ""
        }
    }

	changeHandler = (event) => {
		this.setState({
			[event.target.name]: event.target.value
		});
	};

    handleSubmit = (event) => {
        event.preventDefault();
        console.log(this.state);
    }

    render() {
        return (
            <div>
                <form>
                    <br /><br />
                    <input type="text" name="UserName" placeholder="User Name" onChange={this.changeHandler}/> 
                    <br /><br />
                    <input type="text" name="UserMessage" placeholder="Message" onChange={this.changeHandler}/>  
                    <br /><br />
                    <button onClick={this.handleSubmit}>Submit</button>
                </form>
            </div>
        )
    }
}

export default UserForm

Now run the application and go to the browser and open the console using command/ctrl + options/alt + i. Go to the Console tab, fill your form and press the submit button. You will see a JSON object printing in the console.

React State

At this note, we will end our part 2 of ReactJS. We will learn more about React in the upcoming parts. Till then you can try various things with react. If you have any questions or any concept is not clear or I have missed covering it then feel free to comment down in the comments section.

My Twitter and Github Handle.