There are multiple ways to compose JSX, mainly through elements and components.
- Elements: variables that contain JSX
- Components: functions that return JSX
In this example we explore differences on how to work with elements and components in React.
import React from 'react';
// One element
const element = <h1>I'm a singular element</h1>;
// An array of elements
const elements = [
<li>Element number 1</li>,
<li>Element number 2</li>,
<li>Element number 3</li>,
<li>Element number 4</li>,
<li>Element number 5</li>,
];
// A button component
function Button() {
return <button>I'm a button</button>;
}
// The main app is also a component
export default function App() {
return (
<div>
{/* Render an element */}
{element}
{/* Render an array of elements */}
<ul>{elements}</ul>
{/* Render a component */}
<Button />
</div>
);
}
Ways to write components
The way we write React components has evolved over time. Initially, we wrote React components without JSX, then transitioned to class components, and now, we primarily use functional components.
Components without JSX
Before JSX, React components were written using plain JavaScript. This approach is less common today but is still useful to understand, especially when working with code that dynamically creates components.
import React from 'react';
// Component without JSX
function MyButton(props) {
return React.createElement('button', {
children: props.children,
});
}
export default function App() {
return (
<div>
<MyButton>Button without JSX</MyButton>
</div>
);
}
Class components
Class components were the standard way to write components before the introduction of hooks in React 16.8. They are defined using ES6 classes and extend from React.Component
.
import React from 'react';
// Class component
class MyButton extends React.Component {
render() {
return <button>{this.props.children}</button>;
}
}
export default function App() {
return (
<div>
<MyButton>Button as a class component</MyButton>
</div>
);
}
Functional components
Functional components are simpler and more concise than class components. They are essentially JavaScript functions that return JSX. With the addition of hooks, functional components can now handle state and side effects, making them powerful and versatile.
import React from 'react';
// Functional component
function MyButton(props) {
return <button>{props.children}</button>;
}
export default function App() {
return (
<div>
<MyButton>Button as a functional component</MyButton>
</div>
);
}