Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

JSX and Component Basics

JSX (JavaScript XML) and Component Basics in React.js

JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. In React.js, JSX is used to define the structure and appearance of user interfaces. Components are the building blocks of React applications. Here's an overview of JSX and React components:

JSX (JavaScript XML):

1. JSX Elements:

  • JSX allows you to define elements that look similar to HTML elements but are actually JavaScript objects representing the DOM elements.
  • Example of a JSX element:
const element = <h1>Hello, JSX!</h1>;
     

 

2. Embedding Expressions:

  • You can embed JavaScript expressions inside JSX using curly braces {}.
  • Example:
    const name = 'John';
    const greeting =

    Hello, {name}!

    ;
           

     

     

3. Attributes in JSX:

  • JSX attributes use camelCase naming, like className instead of class and onClick instead of onclick.
  • Example:
const element = <button className="btn" onClick={handleClick}>Click me</button>;
   

 

4. Self-Closing Tags:

  • For elements without children, self-closing tags are used just like in HTML.
  • Example:
const image = <img src="image.jpg" alt="An image" />;
       

 

React Components:

1. Creating Components:

  • In React, you can create reusable UI components as JavaScript functions or classes.
  • Functional component example:
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
     

 

  • Class component example:
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
   

 

2. Rendering Components:

  • To render a React component, you simply include it in JSX as if it were an HTML element.
  • Example:
    const element = <Welcome name="John" />;

 

3. Props (Properties):

  • Components can receive data through props, which are read-only and help pass data from parent to child components.
  • Example:
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Alice" />;
     

 

4. Component Composition:

  • You can compose components by nesting them within each other to build complex UIs.
  • Example:
       function App() {
  return (
    <div>
      <Welcome name="Alice" />
      <Welcome name="Bob" />
    </div>
  );
}

 

5. Class Components vs. Functional Components:

  • Functional components are simpler and used for most scenarios.
  • Class components have additional features like state management and lifecycle methods, but they have more boilerplate.