Home > OS >  Next JS how to order the price of products using two buttons receiving data?
Next JS how to order the price of products using two buttons receiving data?

Time:06-13

I want to create two buttons to sort an array from lowest price to highest price. the data import is from data props, my handles sort only price the array but i want sort all items array

function Products({ data }) {


    const productPrice = data.map(product => product.price)
   

    const [sortPrice, setSortPrice] = useState(productPrice)

    // I don't know what logic I have to use in the useEffect

    useEffect(() => {

        setSortPrice()
    }, [sortPrice])

    function handleHigh(e) {
        setSortPrice(
            productPrice.sort((a, b) => a - b)
        )
    }

    console.log(sortPrice)

    function handleLow(e) {
        setSortPrice(
            productPrice.sort((a, b) => b - a)
        )
    }

CodePudding user response:

I`m tried extract price key with a map function, only necessary using a sort function in the handleLow with the data props

CodePudding user response:

JSX Component

import React from 'react'
import styles from '../../styles/Filter.module.css'


export default function Filter({ handleHigh, handleLow }) {

    return (
        <div>
            <div className={styles.filter}>
                <button className={styles.btn1} onClick={handleHigh}> </button>
                <button className={styles.btn2} onClick={handleLow}>-</button>
            </div>
        </div>
    )
}
  • Related