In Part 1 of this blog post series, we discussed the fundamental requirements to master before learning ReactJS.
Now, we'll focus on getting familiar with the ReactJS syntax.
class to className
When assigning a class to an HTML tag, we use className
instead of class
in ReactJS. And the reason is because in JavaScript, class
is a special keyword and since react app (JSX) is JavaScript-based, className is used to avoid any naming conflict.
For example:
<div className="my-class-name"></div>
Importing and exporting
One of the best reasons why libraries like Reactjs is used in building web application is because of reusable component featured… You can create a component, let’s say Navbar and use the same piece of code for your entire application.
How is this possible? By importing and exporting the component and we can import modules, images etc.
Here's an example:
import React from 'react';
function App() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
);
}
export default App;
Here we are importing “REACT” package from a source called react
so that we can use the foundational code base to build our application.
And then we are exporting the component so that we can use it somewhere else as well.
React Hooks
Another essential feature of ReactJS is React Hooks.
These are reusable functions that give access to managing and manipulating states and lifecycles in ReactJS.
Before React v16.8, developers used a class method for declaring components, but it was difficult to understand the syntax as the project got larger. Now, almost all React developers use functional components over class-based component declarations.
The two most commonly used React Hooks are useState
and useEffect
. Other Hooks exist, and developers can also create their hooks by extending React Hooks.
With this knowledge, let's build a simple ReactJS application.
Building a Simple ReactJS Application
Our simple app will feature a form page that takes user data and logs the result to the console when the user clicks the submit button. Since we don't have a backend endpoint, we won't submit the data to the server.
Here's an overview of what we need to do:
- Bootstrap a React project
- Clean up the starter files
- Create the form
Let's get started!
Step 1: Bootstrap a React Project
To bootstrap a React project, we'll use create-next-app
. Open your terminal, navigate to the directory where you want to create your project, and run the following command:
npx create-next-app my-app-name
This will create a new React project named my-app-name. Next, navigate to the project directory and start the development server with the following command:
cd my-app-name
npm start
NOTE: You can use any Reactjs framework to build react application such as Next, Vite etc. We are using Nextjs in this tutorial.
Now that your app is up and running, you can it in your browser at http://localhost:3000/.
Step 2. Clean Up the Starter Files
Before we create the form, let's clean up the starter files. Delete everything in the src
directory except for index.js and App.js. We'll also remove the contents of App.js.
Our App.js file should look like this:
import React from 'react';
function App() {
return (
<div className="App">
</div>
);
}
export default App;
Also, don't forget to remove all the imports of the files deleted otherwise, your app will throw error because you're importing files that no longer exist.
You can try searching for the names of the files and folders deleted in your code editor and remove all the imports.
If you're using Vs code, it will warn you and tell you where those dead imports are.
Step 3. Create the Form
Let's add a form to our App.js
file. We'll create a state for the form input values using useState
hook. Here's the complete code for our App.js file:
import React, { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
function handleSubmit(event) {
event.preventDefault();
console.log(`Name: ${name}\nEmail: ${email}\nPhone: ${phone}`);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={event => setName(event.target.value)}
/>
</label>
<br />
<label>
Email:
<input
type="email"
value={email}
onChange={event => setEmail(event.target.value)}
/>
</label>
<br />
<label>
Phone:
<input
type="tel"
value={phone}
onChange={event => setPhone(event.target.value)}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
export default Form;
Code explained:
In the code above, we are using the useState
hook to manage the state (or store the initial value) of our form inputs. We are also defining a function called handleSubmit
that will be called when the form is submitted.
This function will prevent the default form submission behavior such as reloading the form page (we use event.preventDefault()
fot that purpose) and log the form data to the console.
Also we are handling change on our <input />
to listen to whatever user type. If you don't handle change on forms, the you will not get input value from the user.
There are other ways to get value from form aside handleChange but I won't digress to that in this blog post
Also, notice that with pure JavaScript, you will have to get the id of a particular element (say button) and apply addEventListener
to it like this:
const button = document.querySelector(“.btn”)
button.addEvenListener(“click” function())
to this in reactjs
<button onClick={() => function()} />
Inside the return statement, we are using JSX to define our form structure. We are using the value attribute to bind the state of our inputs and the onChange event to update their state when they change.
Now, we need to import our Form component into our App.js file and render it inside the div element we created earlier.
import React from 'react';
import './App.css';
import Form from './Form';
function App() {
return (
<div className="App">
<h1>My React App</h1>
<Form />
</div>
);
}
export default App;
Step 3. Test and deploy
Now that our form page is complete, we can test it by running our application with the following command:
npm start
This will open up a new browser window at http://localhost:3000/ with our application running.
Enter some data into the form and click the submit button. You should see the form data logged to the console.
Congratulations, you have built your first React application!
Conclusion: React.js is a simple frontend library
In this tutorial, we learned the basics of Reactjs syntax, including assigning classes, importing and exporting, and React Hooks. We also built a simple form page that takes user data and logs it to the console.
Reactjs is a powerful library for building web applications, and this tutorial is just the beginning. There is much more to learn, but hopefully, this tutorial has given you a good foundation to start building your own React applications.
If you have any question, feel free to ask and I together with the community here will be ready to help.
Thank you.
Top comments (0)