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

Time:04-27

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.?

CodePudding user response:

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>

CodePudding user response:

You could use a state that representsindex and the slice method:

const [index, setIndex] = useState(0);

return (
<button onClick={() => setIndex(prevIndex => prevIndex   1)}>Click Me</button>
{array.slice(0, index).map(x => <p>{x} </p>)}
);
  • Related