Table of Contents
Introduction
React JS is a popular JavaScript library for building user interfaces. React relies on several core building blocks to create complex user interfaces. In this tutorial, we will provide a deep understanding of these building blocks and how they are used in React JS.
Components
Components are the building blocks of React. A component is a reusable piece of code that represents a part of a user interface. Components can be reused throughout an application to create complex user interfaces.
There are two types of components in React:
- Functional Components: A function that returns a React element. These are simpler components that do not have state or lifecycle methods.
- Class Components: A class that extends the React.Component class. These components have state and lifecycle methods.
JSX
- JSX is a syntax extension to JavaScript that allows developers to write HTML-like syntax in their JavaScript code. JSX allows developers to write components as a combination of JavaScript and HTML. This makes it easier to read and understand code.
Here’s an example of JSX in React:
function Hello(props) {
return <h1>Hello, {props.name}!</h1>;
}
Props
Props (short for “properties”) are used to pass data between components. Props are passed from a parent component to a child component through attributes.
Here’s an example of using props in React:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Greeting name="John" />
<Greeting name="Jane" />
</div>
);
}
In this example, the Greeting
component is passed a name
prop from its parent App
component.
State
State is used to manage data within a component. State is managed internally by a component and can be changed by the component itself.
Here’s an example of using state in React:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.increment()}>Increment</button>
</div>
);
}
}
In this example, the Counter
component has an internal state that manages a count value. The count value is incremented when the Increment
button is clicked.
Conclusion
In summary, React JS has several core building blocks that are used to create complex user interfaces. Components, JSX, props, and state are the foundation of React JS development. By understanding these building blocks, developers can create scalable and maintainable applications.