Home > Enterprise >  React js. Array elements show more show less with useHooks useState
React js. Array elements show more show less with useHooks useState

Time:10-18

I am kinda fresh to react and useState hooks (still learing). I want to create show more/less button with use of Array and React hooks. I came across this code with exact result i want to achieve - showing some part of an array, and then showing the rest/ returning to previous state.

The thing is, the code is written with use of class components. I never even learned them, useState is more recent.

How to achieve something like this, but with use of state hook (useEffect?) if is it possible ?

https://jsbin.com/wowaluwipu/1/edit?html,js,output

class Application extends React.Component {
  constructor() {
    super()   
    this.state = {
      cars: [
      { "name" : "Audi", "country" : "Germany"},
      { "name" : "BMW", "country" : "Germany" },
      { "name" : "Chevrolet", "country" : "USA" },
      { "name" : "Citroen", "country" : "France" },
      { "name" : "Hyundai", "country" : "South Korea" },
      { "name" : "Mercedes-Benz", "country" : "Germany" },
      { "name" : "Renault", "country" : "France" },
      { "name" : "Seat", "country" : "Spain" },
    ],
      itemsToShow: 3,
      expanded: false
    }

    this.showMore = this.showMore.bind(this);
  }
  
  showMore() {
    this.state.itemsToShow === 3 ? (
      this.setState({ itemsToShow: this.state.cars.length, expanded: true })
    ) : (
      this.setState({ itemsToShow: 3, expanded: false })
    )
  }
  
  render() {
    return <div className="container">
      <h3>Click show more to see more data</h3>
      <div className="row">
        <h3>List of Cars</h3>
        <ul>
          {this.state.cars.slice(0, this.state.itemsToShow).map((car, i) => 
           <li key={i}>{car.name} - {car.country}</li>
          )}
        </ul>
      </div>

CodePudding user response:

Either way, mine works as well as the others. Just in a bit of a different way.

 import React, { useState } from 'react'

function Stacks() {
    const [itemsToShow, setItemsToShow] = useState(3);

    const cars = [
      { "name" : "Audi", "country" : "Germany"},
      { "name" : "BMW", "country" : "Germany" },
      { "name" : "Chevrolet", "country" : "USA" },
      { "name" : "Citroen", "country" : "France" },
      { "name" : "Hyundai", "country" : "South Korea" },
      { "name" : "Mercedes-Benz", "country" : "Germany" },
      { "name" : "Renault", "country" : "France" },
      { "name" : "Seat", "country" : "Spain" },
    ];

    const showmore = () => {
        setItemsToShow(cars.length)
    }

    const showless = () => {
        setItemsToShow(3)
    }

    return (
        <div>
            {cars.slice(0, itemsToShow).map((car, index) => <li key={index}>{car.name} - {car.country} </li>)}
            {(itemsToShow === 3) ? <button onClick={showmore}>Show More</button>: <button onClick={showless}>Show Less</button>}
        </div>
    )
}

Might not be the efficient way, the only difference is I took out the onliner code from show more and made a separate function show less that resets the original state value which is 3.

I have the same problem when I was just starting in React that I normally see Class Components in tutorials.

CodePudding user response:

hello i had the same problem ,but thanks to help of others it is much clearer (i cloudnt test if it works myself but that should be it)

        import { useState } from "react";

  function App() {
    // const [state, setstate] = useState(initialState) // this is how it initially is
    const [data, setData] = useState({
      cars: [
        { name: "Audi", country: "Germany" },
        { name: "BMW", country: "Germany" },
        { name: "Chevrolet", country: "USA" },
        { name: "Citroen", country: "France" },
        { name: "Hyundai", country: "South Korea" },
        { name: "Mercedes-Benz", country: "Germany" },
        { name: "Renault", country: "France" },
        { name: "Seat", country: "Spain" },
      ],
      itemsToShow: 3,
    }); // i named it data youcan name it whatever suits you

    const showMore = () => {
      data.itemsToShow === 3
        ? // ...data is a spread of the state, that means have all the data and change that
          // particular one, in that case  "itemsToShow"
          setData({ ...data, itemsToShow: data.cars.length })
        : setData({ itemsToShow: 3 });
    };

    return (
      <div className="container">
        <h3>Click show more to see more data</h3>
        <div className="row">
          <h3>List of Cars</h3>
          <ul>
            {data.cars.slice(0, data.itemsToShow).map((car, i) => (
              <li key={i}>
                {car.name} - {car.country}
              </li>
            ))}
          </ul>
        </div>
        // if the items you want to show are equal to the legth of your car list
        then hide the button
        {data.itemsToShow < data.cars.length && (
          <button onClick={showMore}>Show more</button>
        )}
      </div>
    );
  }

  export default App;

generally you get rid of ,"this", "this.state", and instead of "this.setState" you put your hook directly like "setNewThings" or "SetCrazyStuff", or what so..

You'll get the hang of it with more practice, hope that helps

  • Related