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,

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.