Mark As Completed Discussion

Components and Props

In React, components are the building blocks of the user interface. They encapsulate the functionality and rendering logic of a part of the UI. Components can be reused and composed together to create complex UIs.

To define a component, we use the class syntax in JavaScript. Here's an example of a basic component:

JAVASCRIPT
1class Welcome extends React.Component {
2  render() {
3    return <h1>Hello, {this.props.name}!</h1>;
4  }
5}

In the code above, we define a Welcome component that renders a h1 tag with a personalized greeting. The name is passed in as a prop.

To use a component, we can simply include it in the JSX code. Here's an example:

JAVASCRIPT
1const element = <Welcome name="Alice" />;
2
3ReactDOM.render(
4  element,
5  document.getElementById('root')
6);

In the code above, we create an instance of the Welcome component and pass the name prop as "Alice". We then render the component by calling ReactDOM.render() with the component element and a DOM element to mount it.

When rendering the component, React replaces the {this.props.name} expression with the value of the name prop, resulting in the output "Hello, Alice!".

Components can have multiple props, and the prop values can be of any type, including strings, numbers, booleans, or even other components. Props allow us to pass data from a parent component to a child component.

In addition to props, components can also have state, which allows them to manage and update their own data. We'll explore state in more detail in the next section.

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