Leo Forney
Leo Forney

Reputation: 57

React list isn't re-rendering table after sorting elements in state

I'm having issues with React not rendering after sorting the table I have. It seems to update the state variable and I'm using setState, I just have no idea why it's not showing the new updated data. Here's my code

class CarRow extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            manufacturer: this.props.passedCar.manufacturer,
            model: this.props.passedCar.model,
            year: this.props.passedCar.year,
            stock: this.props.passedCar.stock,
            price: this.props.passedCar.price,
        }

        this.state.price = this.state.price.toLocaleString(undefined, {maximumFractionDigits: 2})
    }

    handleCount(value) {
        this.setState((prevState) => ({stock: prevState.stock + value}));
    }

    render() {
        return (<tr>
            <td>{this.state.manufacturer}</td>
            <td>{this.state.model}</td>
            <td>{this.state.year}</td>
            <td>{this.state.stock}</td>
            <td>${this.state.price}</td>
            <td>
                <button onClick={() =>
                    this.handleCount(1)}>
                    Increment
                </button>
            </td>
        </tr>)
    }
}


class App extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            descending: true,
            cars: [
                {
                    "manufacturer": "Toyota",
                    "model": "Rav4",
                    "year": 2008,
                    "stock": 3,
                    "price": 8500
                },

                {
                    "manufacturer": "Toyota",
                    "model": "Camry",
                    "year": 2009,
                    "stock": 2,
                    "price": 6500
                },

                {
                    "manufacturer": "Toyota",
                    "model": "Tacoma",
                    "year": 2016,
                    "stock": 1,
                    "price": 22000
                },

                {
                    "manufacturer": "Dodge",
                    "model": "Charger",
                    "year": 2013,
                    "stock": 2,
                    "price": 16000
                },

                {
                    "manufacturer": "Ford",
                    "model": "Mustang",
                    "year": 2009,
                    "stock": 1,
                    "price": 8000
                },

            ]
        };
    }

    sortCars() {
        var carsSorted = JSON.parse(JSON.stringify(this.state.cars));
        carsSorted.sort((a, b) => (this.state.descending ? b.price - a.price : a.price - b.price));
        this.setState({cars: carsSorted});
        this.setState({descending: !this.state.descending});
    }

    render() {
        return (
            <table>
                <thead>
                <tr>
                    <th>manufacturer</th>
                    <th>model</th>
                    <th>year</th>
                    <th>stock</th>
                    <th onClick={() =>
                        this.sortCars()}>price
                    </th>
                    <th>Option</th>
                </tr>
                </thead>
                <tbody>
                {this.state.cars.map((car) => {
                    return <CarRow passedCar={car}/>;
                })}
                </tbody>
            </table>
        );
    };
}

ReactDOM.render(<App/>, document.getElementById("app"))

I've tried also creating a separate item for the table component, but it didn't seem to work. I'm pretty new to react, and I don't know alot about it.

If I could get some help with this, that would be great, thanks.

Upvotes: 2

Views: 777

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370669

You need to give your child CarRow components a key when iterating over them so they get re-rendered properly. Find something unique that'll identify a row, and set that as the key. For example, you could put together the model and the year:

return <CarRow key={car.model + '_' + car.year} passedCar={car}/>;

Then they'll appear sorted in the proper direction as desired when rendering again.

class CarRow extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            manufacturer: this.props.passedCar.manufacturer,
            model: this.props.passedCar.model,
            year: this.props.passedCar.year,
            stock: this.props.passedCar.stock,
            price: this.props.passedCar.price,
        }

        this.state.price = this.state.price.toLocaleString(undefined, {maximumFractionDigits: 2})
    }

    handleCount(value) {
        this.setState((prevState) => ({stock: prevState.stock + value}));
    }

    render() {
        return (<tr>
            <td>{this.state.manufacturer}</td>
            <td>{this.state.model}</td>
            <td>{this.state.year}</td>
            <td>{this.state.stock}</td>
            <td>${this.state.price}</td>
            <td>
                <button onClick={() =>
                    this.handleCount(1)}>
                    Increment
                </button>
            </td>
        </tr>)
    }
}


class App extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            descending: true,
            cars: [
                {
                    "manufacturer": "Toyota",
                    "model": "Rav4",
                    "year": 2008,
                    "stock": 3,
                    "price": 8500
                },

                {
                    "manufacturer": "Toyota",
                    "model": "Camry",
                    "year": 2009,
                    "stock": 2,
                    "price": 6500
                },

                {
                    "manufacturer": "Toyota",
                    "model": "Tacoma",
                    "year": 2016,
                    "stock": 1,
                    "price": 22000
                },

                {
                    "manufacturer": "Dodge",
                    "model": "Charger",
                    "year": 2013,
                    "stock": 2,
                    "price": 16000
                },

                {
                    "manufacturer": "Ford",
                    "model": "Mustang",
                    "year": 2009,
                    "stock": 1,
                    "price": 8000
                },

            ]
        };
    }

    sortCars() {
        var carsSorted = JSON.parse(JSON.stringify(this.state.cars));
        carsSorted.sort((a, b) => (this.state.descending ? b.price - a.price : a.price - b.price));
        this.setState({cars: carsSorted});
        this.setState({descending: !this.state.descending});
    }

    render() {
        return (
            <table>
                <thead>
                <tr>
                    <th>manufacturer</th>
                    <th>model</th>
                    <th>year</th>
                    <th>stock</th>
                    <th onClick={() =>
                        this.sortCars()}>price
                    </th>
                    <th>Option</th>
                </tr>
                </thead>
                <tbody>
                {this.state.cars.map((car) => {
                    return <CarRow key={car.model + '_' + car.year} passedCar={car}/>;
                })}
                </tbody>
            </table>
        );
    };
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

Upvotes: 4

Related Questions