Mark As Completed Discussion

React Components

React components are the building blocks of any React application. They are reusable pieces of code that define the structure and behavior of a part of the user interface.

In React, components can be created using either class components or function components.

Class Components

Class components are created by extending the React.Component class. They have a render() method that returns the component's HTML representation. Class components are useful when the component needs to have its own state or lifecycle methods.

Here's an example of a class component:

SNIPPET
1import React from 'react';
2
3class Button extends React.Component {
4  render() {
5    return (
6      <button>{this.props.label}</button>
7    );
8  }
9}

Function Components

Function components are created by writing a JavaScript function that returns the component's HTML representation. Function components are simpler and easier to write compared to class components. They are useful when the component doesn't need to manage its own state or lifecycle methods.

Here's an example of a function component:

SNIPPET
1import React from 'react';
2
3function Button(props) {
4  return (
5    <button>{props.label}</button>
6  );
7}

To use a component, you can simply import it and include it in the JSX code of another component. Here's an example of how to use the Button component:

SNIPPET
1import React from 'react';
2import Button from './Button';
3
4function App() {
5  return (
6    <div>
7      <h1>Example App</h1>
8      <Button label="Click Me" />
9    </div>
10  );
11}

In this example, the App component includes the Button component, which will render a button with the label "Click Me".

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment