Skip to content

Instantly share code, notes, and snippets.

@hollygood
Last active May 17, 2021 01:45
Show Gist options
  • Save hollygood/8e963a843845096dd4a9f543efd71683 to your computer and use it in GitHub Desktop.
Save hollygood/8e963a843845096dd4a9f543efd71683 to your computer and use it in GitHub Desktop.
Some React Best Practices

React Best Practices

Map Function for Dynamic Rendering of Arrays

render () {
  let cartoons = [ "Pika", "Squi", "Bulb", "Char" ];
  return (
  <ul>
    {cartoons.map(name => <li key={name}>{name}</li>)}
  </ul>
  );
}

ES6 spread functions can be used to send a whole list of parameters in an object by using Object.keys().

render () {
  let cartoons = {
  "Pika": {
    type: "Electric",
    level: 10
  },
  "Squi": {
    type: "Water",
    level: 10
  },
  "Bulb": {
    type: "Grass",
    level: 10
  },
  "Char": {
    type: "Fire",
    level: 10
  }
  };
  return (
  <ul>
    {Object.keys(cartoons).map(name => <Cartoons key={name} {... cartoon[name]} />)}
  </ul>
  );
}

class Item extends Component {
  state = {
  listitems: [
    {
      id: 0,
      context: "Primary",
      modifier: "list-group-item list-group-item-primary"
    },
    {
      id: 1,
      context: "Secondary",
      modifier: "list-group-item list-group-item-secondary"
    },
    {
      id: 2,
      context: "Success",
      modifier: "list-group-item list-group-item-success"
    },
    {
      id: 3,
      context: "Danger",
      modifier: "list-group-item list-group-item-danger"
    },
    {
      id: 4,
      context: "Warning",
      modifier: "list-group-item list-group-item-warning"
    }
  ]
  };
 
  render() {
  return (
    <React.Fragment>
      <ul className="list-group">
        {this.state.listitems.map(listitem => (
          <li key={listitem.id} className={listitem.modifier}>
            {listitem.context}
          </li>
        ))}
      </ul>
    </React.Fragment>
  );
  }
}

Dynamic Rendering with && and the Ternary Operator

class FilterResult extends Component {
  render () {
  let { filterResults } = this.props;
  return (
    <section className="search-results">
      { filterResults.length > 0 &&
        filterResults.map(index => <Result key={index} {... results[index] />)
      }
      { filterResults.length === 0 &&
        <div className="no-results">No results</div>
      }
    </section>
  );
  }
}

// Better
class FilterResult extends Component {
  render () {
  let { filterResults } = this.props;
  return (
    <section className="search-result">
      { filterResults.length > 0
        ? filterResults.map(index => <Result key={index} {... filterResults[index] />)
        : <div className="no-result">No results</div>
      }
    </section>
  );
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment