One. Conditional rendering

You can use if… as in JavaScript. Else render the page, or you can use the ternary operator

function UserGreeting(props) { return <h1>Welcome back! </h1>; } function GuestGreeting(props) { return <h1>Please sign up.</h1>; } function Greeting(props) { const isLoggedIn = props.isLoggedIn; // Conditional render component if (isLoggedIn) {return <UserGreeting />; } return <GuestGreeting />; } ReactDOM.render( // Try changing to isLoggedIn={true}: <Greeting isLoggedIn={false} />, document.getElementById('root') );Copy the code

List rendering

1. List syntax

In addition to the Map method, you can also use other loop methods in JavaScript

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li>{number}</li>
);

ReactDOM.render(
  <ul>{listItems}</ul>,
  document.getElementById('root')
);
Copy the code

2. Key of the list

React needs to know which list elements have changed, and it needs to modify those elements, rather than change them all, to ensure minimal performance cost.

So we need to make sure that the key is unique

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>{number}</li>
);

ReactDOM.render(
  <ul>{listItems}</ul>,
  document.getElementById('root')
);
Copy the code