Element
Elements are anything inside angle brackets
<div></div>
<Greeting />
Component
Define a Component by declaring a function that returns a React Element
function Greeting() {
return <div>Hi there!</div>;
}
Expressions
Use curly braces to embed expressions in JSX
function Greeting() {
let name = "chantastic";
return <div>Hi {name}!</div>;
}
Props
Take props
as an argument to allow outside customizations of your Component.
function Greeting(props) {
return <div>Hi {props.name}!</div>;
}
defaultProps
Specify default values for props
with defaultProps
.
function Greeting(props) {
return <div>Hi {props.name}!</div>;
}
Greeting.defaultProps = {
name: "Guest",
};
Destructuring props
Destructuring assignment is a Javascript feature, it was added to the language in ES2015
let person = { name: "chantastic" };
let { name } = person;
Works with Arrays too.
let things = ["one", "two"];
let [first, second] = things;
Destructuring assignment is used a lot in Functional components. These component declarations below are equivalent:
function Greeting(props) {
return <div>Hi {props.name}!</div>;
}
function Greeting({ name }) {
return <div>Hi {name}!</div>;
}
There’s a syntax for collecting remaining props
into an object.
It’s called rest parameter syntax and looks like this.
function Greeting({ name, ...restProps }) {
return <div>Hi {name}!</div>;
}
Those three dots (...
) take all the remaining properties and assign them to the object restProps
.
JSX Spread Attributes
Spread Attributes is a feature of JSX. It’s a syntax for providing an object’s properties as JSX attributes.
Following the example from above,
We can spread restProps
over our <div>
.
function Greeting({ name, ...restProps }) {
return <div {...restProps}>Hi {name}!</div>;
}
This makes Greeting
super flexible.
We can pass DOM attributes to Greeting
and trust that they’ll be passed through to div
.
<Greeting name="Fancy pants" className="fancy-greeting" id="user-greeting" />
Avoid forwarding non-DOM props
to components.
Destructuring assignment is popular because it gives you a way to separate component-specific props from DOM/platform-specific attributes
function Greeting({ name, ...platformProps }) {
return <div {...platformProps}>Hi {name}!</div>;
}