Creating a Component
Remember, a Functional Component is written as so:
|
|
How not to define a component
A Component must evaluate to a single node. You can’t have an array. So you can’t do the following:
|
|
Use <div>
s to wrap components if you have to.
Using Props in a Component
If you’re wondering about the curly braces in the function arguments
|
|
it’s essentially a short hand for
|
|
which in turn is a shorthand for
|
|
Using the braces to assign variables from objects is called Object Destructuring and was introduced in ES2015.
Detecting Invalid Prop Types
Sometimes, you might get into a situation where you’re passing in the wrong values to your props. React can help you debug these situations using propTypes
. If a given value does not match an assigned PropType
, React will log a warning to identify the issue.
|
|
Assigning Default Props
If you want to fallback to a default value for your props, you can use defaultProps
.
|
|
Forwarding Props
If you’re wrapping a component but want to forward some props to the wrapped component, you can use Object Spreading and the ...rest
syntax when Object Destructuring.
|
|
So doing something like:
|
|
Will evaluate to:
|
|
Using a Component
You need to use Components to create Components. So using your Component is no different than what you did to create it!
|
|
Any nested content is resolved as a children
prop.
Assigning Props
Here’s some different ways you can assign a prop.
|
|
Iterating on Components
If you want to create a number of Elements, you can just provide an expression which resolves to any array of Elements.
|
|
You have to provide a key
prop which is unique for each element of the array. Otherwise, React won’t be able to keep track of which Element is which when running its diffing. So without a key
, if you remove an element, it will re-render the whole tree instead of just removing one Element.