React Components and Properties
React components are functions that return JSX. The JSX returned can be customized through the use of component properties.
Table of Contents
- My First React Component
- CodePen Auto-Imports Dependencies
- Props is Short for Properties
- Components within Component
- Multiple Props
- Destructuring Props
- Destructuring Function Parameters
- Default Props Values
My First React Component
Let’s render a simple React component:
See the Pen Hello React Component by Kyle Geske (@stungeye) on CodePen.
Things to know about React components:
- React components are functions named in CamelCase.
- Functional components return JSX.
- Components are declared as JSX elements of the same name:
<Hello />
📢 Note: We won’t be learning about legacy class-based components.
CodePen Auto-Imports Dependencies
These CodePens were configured to auto-include the React dependencies, so missing from the code are the imports:
import React from "react";
import ReactDOM from "react-dom";
Props is Short for Properties
React components can be made configurable by accepting a single props
parameter.
Let’s update the Hello
component to accept and use a name
property:
function Hello(props) {
return <p>Hello {props.name}</p>;
}
A component’s attributes become properties of the props
object:
<Hello name="Wally" />
<Hello name="Daisy" />
👆 In this example the values of the name
attributes are assigned to props.name
within the declared Hello
components.
Components within Component
To demo props
let’s nest two Hello
components in a new App
component:
See the Pen React Components within Components by Kyle Geske (@stungeye) on CodePen.
👆 Rendering the App
component into the rootElement
on the last line of code.
Multiple Props
Components can accept any number of props. Let’s add a greeting
prop:
See the Pen Multiple Props React by Kyle Geske (@stungeye) on CodePen.
📢 Note: The order of the attributes on a JSX element does not matter.
Destructuring Props
Use a destructuring function parameter to unpack the prop object properties:
See the Pen Destructuring Props React by Kyle Geske (@stungeye) on CodePen.
👆 Instead of props.greeting
and props.name
we now use greeting
and name
within the component.
Destructuring Function Parameters
Destructuring can be used for any function parameter in Javascript. For example:
function logLove({ count, animals }) {
console.log(`I love you as much as ${count} ${animals}.`);
}
const data = { count: 42, animals: "Elephants" };
logLove(data);
Resources
Default Props Values
Destructuring the function parameter allows for prop defaults:
See the Pen Default Props Values React by Kyle Geske (@stungeye) on CodePen.
👆 The Hello
component can now be declared with zero, one, or two attributes.