How To Toggle On Order In Reactjs
I am doing sorting in asc and desc. I want to make logic if User click first time I want to update it with name asc, when User click second time I want to update it with name desc.
Solution 1:
You can toggle based on what you have in the state.
getSortedData = () => {
this.setState({
sortedData: this.state.sortedData === "name asc" ? "name desc" : "name asc"
}, () => {
this.getData();
});
};
So this one will work on the following way:
sortedData = "name asc";
console.log(sortedData);
setInterval(function () {
sortedData = sortedData === "name asc" ? "name desc" : "name asc";
console.log(sortedData);
}, 500);
Solution 2:
This is a good question. I think you can do something like that.
classAppextendsReact.Component {
state = {
names: ['Ane', 'Robert', 'Jane'],
asc: true,
};
toggleOrder = () => {
this.setState({
names: this.state.asc
? this.state.names.sort()
: this.state.names.reverse(),
asc: !this.state.asc,
});
}
render() {
const { names, asc } = this.state;
return (
<div><buttononClick={this.toggleOrder}
>
{
asc ? 'des' : 'asc'
}
</button><ul>
{
names.map(name => (
<li>{name}</li>
))
}
</ul></div>
);
}
}
ReactDOM.render(
<App />,
document.querySelector('#app')
);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><divid="app"></div>
Solution 3:
define order
in your component state and initialize it with true.
constructor(props){
super(props);
this.state={
order: true,
sortedData: ''
}
}
getSortedData =() => {
if (this.state.order) {
this.setState({order: false, sortedData: 'name desc' }, () => {
this.getData();
});
} else {
this.setState({order: true, sortedData: 'name asc' }, () => {
this.getData();
});
}
}
Post a Comment for "How To Toggle On Order In Reactjs"