React 101: Components

Henna Singh
5 min readApr 24, 2023

This is a continuation of the React 101 series. The first article can be found at React 101:JSX

What is a component?

React applications are made of components. A component is a small, reusable chunk of code that does only one job. That job is often to render some HTML and re-render it when some data changes.

React components are building blocks that make up a React application. In a website, we can create a component for the search bar, another component for the navigation bar, and another component for the dashboard content itself.

Function Component

Function components are defined by using JavaScript functions. They are the standard in modern React applications to be used along with Hooks.

A function component is defined once and used wherever we like. It returns React JSX. It is mandatory to define the export statement to use it later.

import React from 'react';

function MyComponent() {
return <h1>Hello, I'm a functional React Component!</h1>;
}

export default MyComponent;

It is important to note, the name of a function component starts with a capital letter so React can interpret it as a React component. If it begins with a lowercase letter, React will begin looking for a built-in component such as div and input instead and fail.

Return keyword in Functional Components

Functional components are similar to regular Javascript functions, except that their job is to assemble a portion of the interface based on instructions given.

The instructions can include a combination of markup, CSS, and JavaScript to produce the desired result. It is mandatory to include a return statement.

The function is expected to produce JSX code that can be used to render something onto the browser screen hence a JSX element must be returned.

function BackButton() {
return <button>Back To Home</button>;
}

This is a definition of the component. It does not render on the browser screen yet.

Importing and Exporting React Components

React application has two core files: App.js and index.js.

App.js is a top-level file of the application, and index.js is the entry point. Function components are either created as separate js files or defined in the App.js file. To use them, they have to be exported to index.js file to render.

To export them, we can prefix it with the export declaration and specify if it is a default or named export. In this case, we’ll stick with default. A refresher on export, peruse the MDN web docs.

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

function MyComponent() {
return <h1>Hello world</h1>;
}

export default MyComponent;

//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import MyComponent from './App';

Using and Rendering a Component

A component can be used with an HTML-like syntax that resembles a self-closing tag:

<MyComponent />

To render the component to the browser, methods like .createRoot() and .render() from the react-dom library is used. The code for rendering is written in index.js file.

ReactDOM.createRoot(document.getElementById('app'));
  • document.getElementById('app') returns a DOM element from index.html.
  • .createRoot() receives the DOM element as the first argument and creates a React root container for displaying content.
  • .createRoot() returns a reference to the root container on which you can call methods like .render().

After the root is created, all that’s left to do is call the .render() method on the returned root and display the React component like so:

ReactDOM.createRoot(document.getElementById('app')).render(<MyComponent />);

From here, React will display <MyComponent /> in the root and make it appear on the screen.

In an application fully built with React, this is done only once. From here on, React manages the DOM of the application, and any updates to the UI are taken care of efficiently. Adding more components takes place in the top-level App.js file.

//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import MyComponent from './App';

ReactDOM.createRoot(document.getElementById('app')).render(<MyComponent />);

Multiline JSX in a Component

How does a React component return multi-line HTML?

<blockquote>
<p>
The world is full of objects, more or less interesting; I do not wish to add any more.
</p>
<cite>
<a target="_blank"
href="https://en.wikipedia.org/wiki/Douglas_Huebler">
Douglas Huebler
</a>
</cite>
</blockquote>

A multi-line JSX expression is wrapped in parenthesis in the return statement:

function QuoteMaker() {
return (
<blockquote>
<p>
The world is full of objects, more or less interesting; I do not wish to add any more.
</p>
<cite>
<a target="_blank"
href="https://en.wikipedia.org/wiki/Douglas_Huebler">
Douglas Huebler
</a>
</cite>
</blockquote>
);
};

Variable Attribute in a Component

Following is a JavaScript object named redPanda:

const redPanda = {
src: 'https://upload.wikimedia.org/wikipedia/commons/b/b2/Endangered_Red_Panda.jpg',
alt: 'Red Panda',
width: '200px
};

To render a React Component with redPanda image and its properties, its injected as JavaScript into JSX inside the return statement.

import React from 'react';

const redPanda = {
src: 'https://upload.wikimedia.org/wikipedia/commons/b/b2/Endangered_Red_Panda.jpg',
alt: 'Red Panda',
width: '200px'
};

function RedPanda(){
return (
<div>
<h1>Cute Red Panda</h1>
<img
src={redPanda.src}
alt={redPanda.alt}
width={redPanda.width} />
</div>
);
}

export default RedPanda;

Logic in Function Component

A function component can also have simple calculations that need to happen before returning the JSX element.

function RandomNumber() {
// some logic
const n = Math.floor(Math.random() * 10 + 1);

//a return statement using that logic:
return <h1>{n}</h1>
}

To note: logic is always before the return statement else you will get a syntax error.

Following is an example of a conditional in a function component:

import React from 'react';

const fiftyFifty = Math.random() < 0.5;

// New function component starts here:
function TonightsPlan(){

let output
if(fiftyFifty){
return <h1>Tonight I'm going out WOOO</h1>
} else {
return <h1>Tonight I'm going to bed WOOO</h1>
}
}

export default TonightsPlan

Event Listener and Event Handlers in a Component

The function components can include event handlers. The event handler responds to user interactions on the interface

import React from 'react';

function SubmitButton() {
function handleClick() {
alert('Submission Successful.');
}
return <button onClick={handleClick}>Submit</button>;
}

export default SubmitButton;

Event Handler is passed as a prop to the JSX element. Props are information passed to a JSX tag.

Event Handler functions are defined inside the function component, and by convention start with the word handle followed by the type of event it is handling.

Note that the function is passed without parentheses as it indicates that the event should only be called once the event has happened.

To Recap:

  • React applications are made up of components.
  • Components are responsible for rendering pieces of the user interface.
  • To create components and render them, react and reactDOM must be imported.
  • React components can be defined with Javascript functions to make function components.
  • Function component names must start with a capitalized letter, and Pascal case is the adopted naming convention.
  • Function components must return some React elements in JSX syntax.
  • React components can be exported and imported from file to file.
  • A React component can be used by calling the component name in an HTML-like self-closing tag syntax.
  • Rendering a React component requires using .createRoot() to specify a root container and calling the .render() method on it.
  • Function components can return multiple JSX lines by nesting the elements in a parent element.
  • Variable attributes can be used inside of a React component with JavaScript injections.
  • React components support logic by putting the logic statements above the return statements.
  • Components can conditionally return JSX elements by putting conditional statements inside of the components.
  • Components can respond to events by defining event handlers and passing them to the JSX elements.

Components are at the core of React and they are one of the reasons why React is such a powerful tool!

In the next article, I will write about components interacting.

--

--

Henna Singh

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, and paper crafts. Currently pursuing Full Stack Bootcamp from Nucamp