Multiple React elements or components can be combined to form a component. Components are reusable pieces of UI that can be used in different parts of an application. A component name starts with a capital letter, for example
Components accept props(properties) as arguments which they can consume or pass down further to child components.
We will kick off this tutorial with the following code that
<script>tags that contain
ReactDOM.rendermethod and commented section where component code will be added
root, to render the React application
We will first create a
<Today> component that will display local date and time to the user. For this we will be using
toLocaleTimeString() methods defined in
Date() class. Since this component does not require any props, we will not include them in the function definition.
<Today> component is very generic and can be used across our application by just calling the
In React we can combine two or more components to create a large component. This is also known as component composition in React.
Let’s create a
<Greet> component that will accept the user as a prop and personalize the message for each user. We can access the prop using dot notation or even using object destructuring.
We can include the
<Today/> component just after the
h1 tags to display local date and time to user as follows
Greet component accepts
user as a prop, we can create multiple instances of the same without any interference. A prop can be passed to a component by defining attribute on the component like
<Greet user="Gulshan Saini"/>.
Let’s create multiple instances of the
Greet component and wrap them inside the
App functional component.
You might have noticed that we have wrapped two instances of
Greet inside the
<React.Fragment>. This is required as a component can only have a single root element. React fragments are a special way of wrapping multiple components however they do not introduce new DOM nodes. We could have also wrapped two instances of the
Greet component inside the parent
div element however that would unnecessary create a parent DOM node which might not be required.
See, how easy it is to create reusable components and compose a new component using other components.
The last thing is to merge component in base code that was introduced in the first section and pass
<App/> component inside the
In this tutorial, we learned how to