Stateless
Stateless components are the simplest way to define a component. They are said to be *pure: given a set of props, stateless components always return the same output.
To create a stateless component, we write a JavaScript function that returns JSX:
Notice that Title
is capitalized. When creating custom React components you need to capitalize the name of the component. This lets the JSX transpiler know that this is a custom component, and not a built-in HTML element.
As it stands, our Title component isn't very re-usable though, since it will always return 'Hello World' as its value. To create components that are generic and re-usable, we'll need to be able to pass them attributes, which will be the subject of the next section.
Passing data to our component
Specifying attributes with JSX
The simplest way to explain component props would be to say that they function similarly to HTML attributes. In other words, props provide configuration values for the component.
We'll need to slightly update the implementation of the Title
component to read the value
attribute from it's props:
Prop Types
Props can be any valid JavaScript expression:
String
Number
Array
Object
Function
They can also span on multiple lines for easier readability.
Here's an example using a combination of different expressions:
Note: As you may have noticed, Numbers, Arrays, Objects, and Functions must be wrapped within curly braces.
Passing children to Components
Passing children to components is as simple as
To be able to do that, you will have to modify your existing Title
component to use props.children
as follows:
To add some specific CSS you can create a Title.css
file that you will import in Title.js
as follow:
Last updated