Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make an array element appear on by one after the button is pressed in React JS?

import ReactDOM from 'react-dom';
import React, {useState} from 'react';
function App() {
  const [arr, setArr] = useState(["bmw", "mercedes", "audi"]);
  let result;
  let i = 0;
  function Add() {
  ????  
    
  }
  return(
    <div>
      <button onClick={Add}>Add item</button>
      <div>{arr.map(x => <p>{x}</p>)}</div>
    </div>
  )
}
  
  
ReactDOM.render(<App />, document.getElementById("root"));

This code above just prints all the array elements at once. How do I make ’em appear one by one after clicking the button (one click – arr[0] is displayed, second click – arr[1] is displayed etc.?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Add a new state to update the index, and have the button call that function. Then call another function that slices off the array elements up to the index, map over that array and return some JSX.

const { useState } = React;

function Example() {

 const [arr, setArr] = useState(['bmw', 'mercedes', 'audi']);

 // Add a new state for the index
 const [index, setIndex] = useState(0);

  // Click the button - update the index
  function addElement(arr) {
    setIndex(index + 1);
  }

  // Return some JSX by slicing the array up
  // to the index, and then `map` over that array
  // and return some divs
  function getElements(arr, index) {
    return arr.slice(0, index).map(el => {
      return <div>{el}</div>;
    });
  }
  
  return (
    <div>
      <button onClick={addElement}>Add item</button>
      {getElements(arr, index)}
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading