In this tutorial, we'll explore the world of React.js components. We'll look into the two primary ways of creating components in React: functional components and class components. We'll walk through the creation of each type and discuss their differences.
By the end of this tutorial, you'll be able to:
Prerequisites:
Functional components are JavaScript functions. They can either be declared with function declaration or as an arrow function.
Here's an example of a simple functional component:
// This is a functional component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Class components are ES6 classes. They should always extend React.Component
and have a render
method.
Here's an example of a simple class component:
// This is a class component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Here are some practical examples for better understanding:
// This is a functional component
function Welcome(props) {
// We return some JSX that we want this component to render
return <h1>Hello, {props.name}</h1>;
}
In this example, Welcome
is a functional component. We pass props
to it and use these props
to output dynamic content within the JSX that we return.
// This is a class component
class Welcome extends React.Component {
render() {
// We return some JSX that we want this component to render
return <h1>Hello, {this.props.name}</h1>;
}
}
In this example, Welcome
is a class component. It extends React.Component
, so we have access to this.props
in the render
method.
Next steps would be to delve deeper into the lifecycle methods of class components and the useState
and useEffect
hooks in functional components.
Solution:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Solution:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Continue practicing by creating more complex components with multiple props and different types of data.