React: Use Array.map() to Render Elements

rthefounding

Randy Rivera

Posted on November 16, 2021

React: Use Array.map() to Render Elements
  • Using Array.map() is extremely useful in the sense that often than not, in reacive programming, a programmer has no way to know what the state of an application is until runtime, because so much depends on a user's interaction with that program. As programmers we need to write the code to correctly handle that unknown state ahead of time.
  • Code:
const textAreaStyles = {
  width: 235,
  margin: 5
};

class MyToDoList extends React.Component {
  constructor(props) {
    super(props);
    // Change code below this line

    // Change code above this line
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  handleSubmit() {
    const itemsArray = this.state.userInput.split(',');
    this.setState({
      toDoList: itemsArray
    });
  }
  handleChange(e) {
    this.setState({
      userInput: e.target.value
    });
  }
  render() {
    const items = null; // Change this line
    return (
      <div>
        <textarea
          onChange={this.handleChange}
          value={this.state.userInput}
          style={textAreaStyles}
          placeholder='Separate Items With Commas'
        />
        <br />
        <button onClick={this.handleSubmit}>Create List</button>
        <h1>My "To Do" List:</h1>
        <ul>{items}</ul>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • As you can see there's a textarea and a button, along with a couple of methods that track their states, but nothing is rendered to the page yet.
  • All freeCodeCamp wants us to do is inside the constructor, create a this.state object and define two states: userInput should be initialized as an empty string, and toDoList should be initialized as an empty array. Next, in the render method map over the toDoList array stored in the component's internal state and dynamically render a li for each item.

  • Answer:

class MyToDoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userInput: "",
      toDoList: []
    }
Enter fullscreen mode Exit fullscreen mode
  render() {
    const items = this.state.toDoList.map(l => <li>{l}</li>); 
Enter fullscreen mode Exit fullscreen mode

Use Array.filter to Filter an Array

  • Another method to map is filter, which filters the contents of an array based on a condition, then returns a new array. *Code:
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [
        {
          username: 'Jeff',
          online: true
        },
        {
          username: 'Alan',
          online: false
        },
        {
          username: 'Mary',
          online: true
        },
        {
          username: 'Jim',
          online: false
        },
        {
          username: 'Sara',
          online: true
        },
        {
          username: 'Laura',
          online: true
        }
      ]
    };
  }
  render() {
    const usersOnline = null; // Change this line
    const renderOnline = null; // Change this line
    return (
      <div>
        <h1>Current Online Users:</h1>
        <ul>{renderOnline}</ul>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Here MyComponent's state is initialized with an array of users. Some users are online and some aren't. Let's Filter the array so you see only the users who are online. Then, in the renderOnlinevariable, let's map over the filtered array, and return a li element for each user that contains the text of their username. We'll also include a unique key

*Answer:

  render() {
    const usersOnline = this.state.users.filter(user => user.online); 
    const renderOnline = usersOnline.map(online => <li key = {online.username}>{online.username}</li>); 
Enter fullscreen mode Exit fullscreen mode

Larson, Q., 2019. Frontend Development Libraries. [online] Freecodecamp.org. Available at: https://www.freecodecamp.org/learn/front-end-development-libraries/react

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
rthefounding
Randy Rivera

Posted on November 16, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About