React Components
In this section, we will discuss how to use components to make our application easier to manage.
Next, we will encapsulate a component that outputs "Hello World!" with the component name HelloMessage:
React Example
function HelloMessage(props) {
return <h1>Hello World!</h1>;
}
const element = <HelloMessage />;
ReactDOM.render(
element,
document.getElementById('example')
);
Example Analysis:
- We can define a component using a function:
function HelloMessage(props) { return <h1>Hello World!</h1>; }
You can also use an ES6 class to define a component:
class Welcome extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
- const element = <HelloMessage /> is a user-defined component.
>
Note that native HTML element names start with a lowercase letter, while custom React class names start with an uppercase letter, such as HelloMessage cannot be written as helloMessage. Additionally, a component class can only contain one top-level tag, otherwise, it will throw an error.
If we need to pass parameters to the component, we can use the this.props object, as shown in the following example:
React Example
function HelloMessage(props) {
return <h1>Hello {props.name}!</h1>;
}
const element = <HelloMessage name="tutorialpro"/>;
ReactDOM.render(
element,
document.getElementById('example')
);
In the above example, the name property is accessed via props.name
.
>
Note that when adding attributes, the class
attribute needs to be written as className
and the for
attribute needs to be written as htmlFor
because class
and for
are reserved words in JavaScript.
Composite Components
We can create a component by combining multiple components, separating different functional points of the component.
The following example implements a component that outputs the website name and URL:
React Example
function Name(props) {
return <h1>Website Name: {props.name}</h1>;
}
function Url(props) {
return <h1>Website Address: {props.url}</h1>;
}
function Nickname(props) {
return <h1>Website Nickname: {props.nickname}</h1>;
}
function App() {
return (
<div>
<Name name="tutorialpro.org" />
<Url url="http://www.tutorialpro.org" />
<Nickname nickname="tutorialpro" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('example')
);
In this example, the App component uses the Name, Url, and Nickname components to output the corresponding information.