I'm trying to sort an object before mapping it in reactjs, but every single time I do, I keep getting the TypeError: 0 is read only. I noticed that on load the props are empty, but even when I was trying to check the length of the array and only apply sort when it's higher than 0, or when the array exists to be precised, it would still happen. The moment I try to sort anything, it just stops working.
I would like to be able to sort these via different criteria in the future, but so far I can't even go through regular sorting on render...
I have the below:
ToysList.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class ToysList extends Component {
constructor (props) {
super(props);
this.state = {};
}
render () {
var toys = this.props.toys;
var arr = toys.sort((a,b) => parseFloat(a.price) - parseFloat(b.price));
return (
<div>
<div key="list">
{ arr.map((toy, index) => (
<div key={toy.id}>
{toy.name}:<br/>
Quantity: {toy.quantity}<br/>
Price: {toy.price}<br/>
Rating: {toy.rating}
</div>
)) }
</div>
</div>
);
}
}
ToysList.propTypes = {
toys: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
quantity:PropTypes.number,
price:PropTypes.number,
rating:PropTypes.number,
}),
).isRequired,
};
export default ToysList;
I'd be grateful for any hint with these. Thanks
That could be because sort
mutates the array it works on (it sorts in-place).
If this.props.toys
is immutable then it would throw that error.
Create a copy of the array and sort that.
var toys = this.props.toys.slice();
// var toys = Array.from(this.props.toys);
// var toys = [...this.props.toys];
var arr = toys.sort((a,b) => parseFloat(a.price) - parseFloat(b.price));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With