Some of the basics Syntax of ReactJs are:
To use React, you need to import the React library and other necessary components:
import React from 'react';
import ReactDOM from 'react-dom';
Components are the building blocks of a React application. There are two main types: Functional Components and Class Components.
A simple way to create a component:
function HelloWorld() {
return <h1>Hello, World!</h1>;
}
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');
);
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>;
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')
);
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')
);
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>
);
}