Understanding React JS Components and Props

Understanding React JS Components and Props

React JS is a JavaScript library used for building user interfaces. It follows a component-based architecture, where the UI is divided into reusable and independent components. Components are the building blocks of a React application, and they can be thought of as custom HTML elements.

Components in React can be classified into two types: functional components and class components.

1. Functional Components:
– Functional components are defined as JavaScript functions.
– They are simple and easy to understand.
– They receive props (short for properties) as input and return JSX (JavaScript XML) as output.
– Example:
“`jsx
function Greeting(props) {
return

Hello, {props.name}!

;
}
“`

2. Class Components:
– Class components are defined as JavaScript classes that extend the `React.Component` class.
– They have more features and capabilities compared to functional components.
– They also receive props as input and return JSX as output.
– Example:
“`jsx
class Greeting extends React.Component {
render() {
return

Hello, {this.props.name}!

;
}
}
“`

Props are used to pass data from a parent component to its child component(s). They are read-only and cannot be modified by the child component. Props are passed as attributes to the child component when it is used in the parent component’s JSX.

Example usage of components with props:
“`jsx
function App() {
return (





);
}
“`

In the above example, the `App` component renders two `Greeting` components with different names as props. The `Greeting` component receives the `name` prop and displays a personalized greeting.

Props can be accessed in functional components using the `props` parameter, and in class components using `this.props`.

Overall, components and props are fundamental concepts in React JS that enable the creation of reusable and modular UI elements.