First, conditional rendering

1. Conditional rendering

We can encapsulate different behaviors by creating different components, and then render parts of the corresponding state according to the state of the application

// Define the component wrapper login behavior
class SignIn extends React.Component {
    constructor(props) {
        super(props)
    }
    
    render() {
        return <h1>Please Sign In</h1>}}// Define the component encapsulation registration behavior
class SignUp extends React.Component {
    constructor(props) {
        super(props)
    }
    
    render() {
        return <h1>Please Sign Up</h1>}}// Decide which component to render based on whether the user is logged in
class Greeting extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        if (this.props.isSignUp) {
            return <SignIn />
        } else {
            return <SignUp />
        }
    }
}

ReactDOM.render(
    <Greeting isSignUp={false} />.document.getElementById('app'));Copy the code

2. Block component rendering

In some cases, we want to hide elements by making Render () return null

class Warning extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        if (this.props.isWaring) {
            return <span>Waring!</span>
        } else {
            return null
        }
    }
}

ReactDOM.render(
    <Warning isWarning={false}/>.document.getElementById('app'));Copy the code

3. Element variables

We can use variables to store elements, allowing us to conditionally render parts of a component

class LoginControl extends React.Component {
    constructor(props) {
        // 1, pass props
        super(props);
        // 2
        this.state = {isLoggedIn: false};
        // bind the component instance to the event handler
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogoutClick = this.handleLogoutClick.bind(this);
    }

    handleLoginClick() {
    	this.setState({isLoggedIn: true});
    }

    handleLogoutClick() {
    	this.setState({isLoggedIn: false});
    }

    render() {
        // Use variables to store elements based on conditions
        let greeting;
        let button;

        if (this.state.isLoggedIn) {
            greeting = <h1>Now you are logged in!</h1>;
        	button = <button onClick={this.handleLogoutClick}>Log Out</button>;
        } else {
            greeting = <h1>Please log in!</h1>;
        	button = <button onClick={this.handleLoginClick}>Log In</button>;
        }

        return (
            <div>
                {greeting}
                {button}
            </div>
        );
    }
}

ReactDOM.render(
    <LoginControl isLoggedIn={false} />.document.getElementById('app'));Copy the code

Second, list rendering

1. Render elements

In the React component, we can quickly render list elements using the map() method. Let’s start with a small example

<! DOCTYPE html><html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone"></script>
</head>

<body>
    <div id="app"></div>

    <script type="text/babel">
        class ItemList extends React.Component {
            render() {
                const numbers = [1.2.3.4.5]
                const items = numbers.map((number) = >(<li>{ number }</li>))
                return (<ul>{ items }</ul>)
            }
        }

        ReactDOM.render(
            <ItemList />.document.getElementById('app'));</script>
</body>

</html>
Copy the code

2. Key attributes

In the example above, the elements are displayed normally, but when we open the console, we see a warning message

Warning: Each child in a list should have a unique "key" prop.
Copy the code

We can solve this problem by assigning a key attribute to each list element

class ItemList extends React.Component {
    render() {
        const numbers = [1.2.3.4.5]
        const items = numbers.map((number) = >(
            <li key={ number.toString() }>
                { number }
            </li>
        ))
        return (
            <ul>{ items }</ul>)}}Copy the code

An element’s key should be a unique string that the element has in the list, or an element index can be used as a last resort

class ItemList extends React.Component {
    render() {
        const numbers = [1.2.3.4.5]
        const items = numbers.map((number, index) = >(
            <li key={ index} >
                { number }
            </li>
        ))
        return (
            <ul>{ items }</ul>)}}Copy the code

It is not recommended to use the index as the key if the order of the list items will change

This can lead to performance issues and even component state issues

By default, when we don’t explicitly specify a key, React will use the index as the key for the list item

3. Render components

In addition to rendering multiple elements using the map() method, you can also render multiple components using map(), as shown in an example

class TodoItem extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return ( <h3>{ this.props.title }</h3>)}}class TodoList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            itemList: [{id: 0.title: 'Say Hello'.isDone: true},
                {id: 1.title: 'Say Goodbye'.isDone: false}}}]render() {
        const todoItemList = this.state.itemList.map((item) = > {
            if(! item.isDone) {return ( <li key={ item.id} ><TodoItem title={ item.title} / ></li>)}})return ( <ul>{ todoItemList }</ul> )
    }
}

ReactDOM.render(
    <TodoList />.document.getElementById('app'))Copy the code