REACT

ReactJs Syntax


Some of the basics Syntax of ReactJs are:


1. Importing React

To use React, you need to import the React library and other necessary components:

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

 

2. Creating a Component

Components are the building blocks of a React application. There are two main types: Functional Components and Class Components.

 


2.1 Functional Component

A simple way to create a component:

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

 

2.2 Class Component

Another way to create a component (more powerful, but functional components are preferred for most cases):

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

 

3. Rendering a Component
To display a component, use ReactDOM.render:
 

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

 

4. Using JSX

JSX is a syntax extension that looks similar to HTML and is used in React to describe the UI:

const element = <h1>Hello, World!</h1>;

 

5. Props

Props are used to pass data to components:

function Welcome(props) {
   return <h1>Hello, {props.name}</h1>;
}
ReactDOM.render(
   <Welcome name="Wasif"/>,
   document.getElementById('root')
);

 

6. State (in Class Components)

State is used to manage data that can change over time:
 

class Clock extends React.Component {
 constructor(props) {
   super(props);
   this.state = { date: new Date() };
 }
 
 componentDidMount() {
   this.timerID = setInterval(
     () => this.tick(),
     1000
   );
 }
 
 componentWillUnmount() {
   clearInterval(this.timerID);
 }
 
 tick() {
   this.setState({
     date: new Date()
   });
 }
 
 render() {
   return (
     <div>
       <h1>Hello, World!</h1>
       <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
     </div>
   );
 }
}
 
ReactDOM.render(
 <Clock />,
 document.getElementById('root')
);

 

7. Event Handling

Handling events in React is similar to handling events on DOM elements, but with some syntax differences:
 

function ActionButton() {
 function handleClick() {
   alert('Button clicked!');
 }
 
return (
   <button onClick={handleClick}>
     Click me
   </button>
 );
}