In the early days of web development, you couldn't create a website by combining HTML and JavaScript in the same file. Your HTML code would have to be written separately from your JavaScript code. Thanks to the React framework, this is no longer the case. Not only can both languages now be used in the same file, but JavaScript can also be used inside HTML (and even CSS), making the programmer's life simpler.
In this topic, you will learn what React components are and how you can use them to combine HTML and Javascript.
What are components?
Components are simple, independent, dynamic, reusable pieces of code. As with JavaScript functions, their purpose is to return something. However, React components only return HTML elements.
There are two React component types: Functional components and Class components. But before we discuss the differences between them, let's take a more detailed look at what React components are and how we can create them.
We will mainly focus on Functional components in this topic as they have a simpler syntax.
import React from 'react'
function Card() {
return (
<div className="card">
<div className="input-container">
<input type="text" placeholder="Email"/>
<input type="text" placeholder="Password"/>
</div>
<div className="button-container">
<button>Login</button>
<button>Signup</button>
</div>
</div>
)
}
export default Card;There's no need to panic if the above code snippet seems a bit strange — it's simply a JavaScript function that returns HTML elements.
Let's see how this straightforward component will look on a web page. To do this, you can run the command npm start in the terminal, and the application will start.
As expected, it's a simple HTML page structure with the elements that are defined in the code. Notice that the div elements have the same classes as those specified in the Card function.
Creating components
To create a component, start by running the command npx create-react-app my-app on the terminal. After running the command, open the App.js file that's inside the src folder. Then delete all the code inside this file so the component can be created from scratch.
Let's start by importing the React library. We need to do this because browsers don't understand JSX code. The import tells the compiler that our file contains JSX, meaning that it can be transformed into regular JavaScript.
import React from 'react'As of React version 17.0, this import is only needed if you want to import other functions from the library.
Now we'll define a function named App:
import React from 'react'
function App() {
}At this point, App() is just an empty JavaScript function. To make it a React component, we need it to return at least one HTML element, as shown below:
import React from 'react'
function App() {
return <h1>Hello, Hyperskill</h1>
}So, can we now say that our App function is a React component? The answer is that it depends! How so?
Well, if we tried to run the function as plain JavaScript, the following SyntaxError would be thrown:
// SyntaxError: Unexpected token '<'The reason for this is that JavaScript can't interpret HTML code on its own, which is why we need a framework like React! React uses a compiler named Babel under the hood. Babel transforms all JSX code into JavaScript so that browsers can interpret it. This means that we can say our App function is a React component, providing we run it within the React environment.
Another way to create Functional components is by using arrow functions:
import React from 'react'
const App = () => {
return <h1>Hello, Hyperskill</h1>
}If your function only contains HTML code, you can omit the return keyword, and replace the curly brackets { } with parentheses ( ):
import React from 'react'
const App = () => (
<h1>Hello, Hyperskill</h1>
)However, it's important to remember that the above syntax only works with arrow functions.
More elements
If you want your function to return more than one HTML element, you have to keep a couple of things in mind.
Firstly, if you're going to add more HTML elements to your function, you must always enclose them within a single element.
import React from 'react'
function App() {
return (
<p>Hello</p>
<p>Hyperskill</p>
)
}If you try to run the above code, the compilation will fail with the error shown below:
// SyntaxError: Adjacent JSX elements must be wrapped in an enclosing tagThe solution is quite simple: you need to create one element (such as a <div>) and put the two <p> elements inside it:
import React from 'react'
function App() {
return (
<div>
<p>Hello</p>
<p>Hyperskill</p>
</div>
)
}Secondly, when you have more than one element, they must also be enclosed in parentheses, as you can see in the above example.
Using JavaScript variables
In addition to returning HTML elements, React components can also be used to combine JavaScript, HTML, and even CSS. For now, we'll focus on JavaScript and HTML, but CSS will be covered in a later topic.
Imagine you've got a list of celestial bodies and want to classify them as either stars or planets. It would be a tedious and repetitive task if you had to write down the type of each one in your list.
Fortunately, you can declare variables and use them within the HTML code.
First, you would declare your variables. For example, const star = 'Star';. Don't forget that your variables must be declared before the return statement. It's possible to declare them inside or outside the scope of the function. But as you're only going to be using them within the function, it makes more sense to place them inside.
Next, to use the variables inside the HTML code, you need to enclose them in curly brackets, like this: <p>Type: {star}</p>.
The following example should make this clearer:
import React from 'react'
function App() {
const star = 'Star';
const planet = 'Planet';
return (
<div>
<h2>Celestial Bodies</h2>
<p>Name: Polaris, Type: {star}</p>
<p>Name: Saturn, Type: {planet}</p>
<p>Name: Sirius, Type: {star}</p>
<p>Name: Jupiter, Type: {planet}</p>
<p>Name: Betelgeuse, Type: {star}</p>
<p>Name: Uranus, Type: {planet}</p>
</div>
)
}Your variables will be rendered as an ordinary string, and the result that you'll see on the web page is shown below:
Exporting components
As stated at the beginning of this topic, components are reusable pieces of code. To take advantage of this, you can export them for use in other areas of your application.
To perform an export, you need to use the export keyword and the name of your function. And if your code only includes one component, you must also use the default keyword, as you can see in this example:
import React from 'react'
function App() {
return <h1>Hello, Hyperskill</h1>
}
export default App;Now open the file index.js inside the src folder. In this file, you can import your App function and use it inside root.render:
import { createRoot } from 'react-dom/client';
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(<App />);Notice that the App function is used as a self-closing HTML tag. This enables the render() function to interpret it as a React component. You can also use multiple instances of this function inside render() by enclosing them within a single element:
root.render(
<div>
<App />
<App />
<App />
</div>
);If you run the command npm start now, you should see three h1 elements on your web page.
Class vs. Functional components
The main difference between Class and Functional components is their syntax. While Functional components are simply JavaScript functions, a Class component is a JavaScript class that extends React.Component and has a render() method. Other variations between the components include how we pass props to them and how states are handled. However, there's no need to worry about these differences now as they'll be covered in a future topic.
For the time being, all you really need to know is that Functional components were introduced more recently. And that they have become popular because they are simpler to work with. To illustrate this point, let's make a basic Class component that returns an h1 element:
import React from 'react'
class App extends React.Component {
render() {
return <h1>Hello, Hyperskill</h1>
}
}Conclusion
In this topic, you have learned what React components are and how you can use them. You now know there are two ways to create React components — using functions or classes — and the main differences between them.
Functional components are simple JavaScript functions that return HTML elements. They enable you to combine JavaScript with HTML, making your code more dynamic. They can also be reused in other parts of your application, so you don't have to write the same code twice. Now how about putting this knowledge into practice with some exercises?
Read more on this topic in The Importance of Using Unique Keys in React on Hyperskill Blog.