In-depth JSX
Select the type at run time
error
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
functionStory(props) {// Error! The JSX tag name cannot be an expression.return <components[props.storyType] story={props.story} />;
}
Copy the code
Correct: If you really want to use an expression to determine the React element type, first assign it to a variable that starts with uppercase, not lowercase!
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
functionStory(props) {// Correct! JSX tag names can be variables beginning with an uppercase. const SpecificStory = components[props.storyType];return <SpecificStory story={props.story} />;
}
Copy the code
Extended attributes
function App1() {
return <Greeting firstName="Ben" lastName="Hector"/ >; }function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return<Greeting {... props} />; }Copy the code
Extended properties can be very useful when you build generic containers. However, it can also clutter up the code by passing many unrelated attributes to components that don’t need them. We recommend that you use this syntax with caution.
Context
Context is designed to share data that is considered “global” to a component tree, such as the currently authenticated user, topic, or preferred language.
Fragments
A common pattern in React is to return multiple elements for a component. Fragments allow you to aggregate a list of child elements without adding additional nodes to the DOM.
class Columns extends React.Component {
render() {
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
}
}
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
</table>
Copy the code
Portals
High order component
Specifically, a higher-order component is a function that takes a component as an argument and returns a new component