1
class App extends React.Component {
  constructor() {
    super();
    this.state = {items: []}
  }
  componentWillMount() {
    fetch('https://swapi.co/api/people/?format=json')
      .then(response => response.json())
      .then(({results: items}) => this.setState({items}))
  }
  render() {
    let items = this.state.items
    return (
      <div>

      <ul>
      {items.map((item) =>
        <li key={item.id}>
          {item.name}
        </li>

      )}
    </ul>


      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
  • Here the Array.map render all the properties from object.

    I want only 2 objects using array.map method and render only 2 objects, not all

    how can I do this ?

    Regards,

amitpowerpeace
  • 105
  • 1
  • 2
  • 5

3 Answers3

3

You can do a slice in render: items.slice(0, 2).map(...) or in the API call if you don't need to keep it in state: this.setState({ items: items.slice(0, 2) }).

Use slice(-2) if you want the last 2 items instead.

Roy Wang
  • 11,112
  • 2
  • 21
  • 42
0

Short answer: you can't. The map (and forEach as in the link) don't have a way to break out of them since this is not how they're intended to be used.

However you can avoid returning anything after certain criteria:

<ul>
  {items.map((item, index) =>
    {
     return nothing, hence render nothing if more than 2 items.
     if(index >= 2) return null;

    return(
    <li key={item.id}>
      {item.name}
    </li>);
    }
  )}
</ul>

However, this is also an unclean solution.

A better way is to get a new variable with only the values you want to map though. Since you're already doing let items = this.state.items, you might as well let items = this.state.items.slice(0,2) to get only the first 2 elements and map through them using your normal map in your render.

Obed Parlapiano
  • 3,226
  • 3
  • 21
  • 39
0

You can use Array.filter option for filtering the elements from an array or use Array.slice function.

swapnil2993
  • 1,384
  • 11
  • 15