layout | permalink |
---|---|
page |
/react-component/ |
- The core building blocks of React applications
- Views that represent some chunk of the element tree
- Generate elements during rendering
- Can take inputs from parent components
- Values passed in from the outside are called props (short for "properties")
- Can generate a lot more than HTML
- But we'll use that since we're doing this tutorial in the browser
- Allows HTML-style tags to be freely mixed with JavaScript
- Not part of JavaScript
- JSX is onverted into calls to
React.createElement
during the build step
- JSX is onverted into calls to
- Can be created anywhere a JavaScript expression can be
- Because it gets turned into pure JavaScript
- Create a basic "hello world" component
function Greet() {
return <div>Hello world!</div>;
}
- Mostly write this these days using:
- A "fat arrow" function (which has more sensible treatment of
this
) - Which is assigned to a name
- Which is a constant rather than a variable
- A "fat arrow" function (which has more sensible treatment of
const Greet = () => {
return <div>Hello world!</div>;
}
- In simple cases, can go even further and simply define the return expression:
const Greet = () => <div>Hello world!</div>;
- In all cases,
Greet
is just a function returning text- JSX-to-JavaScript compilation translates
<div>...</div>
into return value
- JSX-to-JavaScript compilation translates
- Add an
export
statement at the bottom to makeGreet
visible to other modules- Part of the new-style ES6 module syntax
- Which isn't yet supported by Node for server-side applications...
export default Greet;
- Using a default export for components is a React convention
Greet.js
will (almost always) exportGreet
and onlyGreet
- Provides a way for elements created by React to be injected into the DOM
- Implementing a React-to-DOM rendering path decouples React elements from the underlying platform
- So React applications can target platforms that don't use a DOM
render
inserts the rendered component to the matched element
-
Props (properties) are data passed into a component from a parent component
-
Used to dynamically change what a component renders or how it behaves
-
Component definition:
export const Greet = (props) => <div>Hello {props.company}</div>;
- The curly braces in the return value interpolate the value of
props.company
into thediv
- Embedded expressions are automatically escaped
- Any JavaScript expression works, even function calls
- Be careful not to call functions with side-effects
- Parent component uses:
<Greet company="Rangle.io" />
- Result:
<div>Hello Rangle.io</div>
export const Greet = ({ company }) => <div>Hello {company}</div>;
- We can use destructuring assignment with
{}
to extract specific fields from objects- Not the same as the use of
{}
for interpolation
- Not the same as the use of