You are here: Home / Topics / Chapter 2: JSX and Components

Chapter 2: JSX and Components

Filed under: React JS Tutorial on 2025-11-19 20:39:51

Introduction to JSX


JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It's used to create React elements and is compiled to JavaScript by Babel.

Creating Components


In React, a component is a small, reusable piece of code that represents a UI element. There are two types of components:

- Functional Components: These are plain JavaScript functions that take props as an argument and return JSX elements.
- Class Components: These are JavaScript classes that extend the `React.Component` class and have a `render` method that returns JSX elements.

Functional Components
 

Here's an example of a functional component:
 

import React from 'react';

function Hello() {
 return <h1>Hello, World!</h1>;
}

export default Hello;

Class Components
 

Here's an example of a class component:
import React, { Component } from 'react';

class Hello extends Component {
 render() {
   return <h1>Hello, World!</h1>;
 }
}

export default Hello;

Rendering Components
 

To render a component, you need to use the `ReactDOM.render` method:
 

import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './Hello';

ReactDOM.render(<Hello />, document.getElementById('root'));

JSX Syntax


JSX syntax is similar to HTML, but with some differences:

- Elements: JSX elements are written in camelCase (e.g., `className` instead of `class`).
- Attributes: JSX attributes are written in camelCase (e.g., `onClick` instead of `onclick`).
- Children: JSX elements can have children, which are elements or text that are nested inside the element.

Example Code


Here's an example of a simple React app that uses JSX and components:


import React from 'react';
import ReactDOM from 'react-dom';

function Header() {
 return <h1>Hello, World!</h1>;
}

function App() {
 return (
   <div>
     <Header />
     <p>This is a paragraph.</p>
   </div>
 );
}

ReactDOM.render(<App />, document.getElementById('root'));


About Author:
A
Ankit Singh     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.