Components are the building blocks of React applications. A component is a reusable piece of code that encapsulates a specific functionality and can be used in different parts of an application. In React, components can be either functional or class-based.
Functional components are simple JavaScript functions that return a React element, like this:
jsx function Greeting(props) { returnHello, {props.name}!
; }
This component takes a single `props` argument and returns an `
` element with the name of the person passed in as a prop.
Class-based components are more powerful and can have additional features like state and lifecycle methods. Here’s an example of a class-based component:
jsx class Greeting extends React.Component { render() { returnHello, {this.props.name}!
; } }
This class-based component is similar to the functional component above, but it’s defined using a class and overrides the `render()` method to return the same `
` element.
Both functional and class-based components can receive data from a parent component through `props`, which are essentially a way to pass data between components. Here’s an example of how to use the `Greeting` component from above:
jsx function App() { return; }
In this example, we’re rendering the `Greeting` component with the `name` prop set to “John”. This will render the `
` element with the text “Hello, John!”.
Overall, components and props are fundamental concepts in React, and they allow you to build complex user interfaces by breaking them down into smaller, reusable pieces of code.