I am new to the react js.
I have an component where I show one icon that is ,
import React, { Fragment } from 'react';
const Sorting = (props) => {
return (
<span className="d-inline-flex">
<i className="fa fa-angle-down" aria-hidden="true" onClick={() => props.sortData(props.type, 'ascending')}></i>
)
}
export default Sorting;
Now, here What I want to do is that ,
when there is a class of down
then it is descending order and if user again click on the icon it will be fa-angle-up
and the onclick of that will get called. So,
what I tried is
import React, { Fragment } from 'react';
const Sorting = (props) => {
const toggleAngle = props.toggleAngle ? <i className="fa fa-angle-down sort-icon" aria-hidden="true" onClick={() => props.sortData(props.type, 'ascending', true)}></i> : <i className="fa fa-angle-up sort-icon" aria-hidden="true" onClick={() => props.sortData(props.type, 'descending', false)}></i>
return (
<span className="d-inline-flex">
{toggleAngle}
</span>
)
}
export default Sorting;
sortData = (key, order, toggleArrow) => {
if (order === 'ascending') {
this.setState({
toggleAngle: toggleArrow
})
this.props.sortAscending(key);
} else {
this.setState({
toggleAngle: toggleArrow
})
this.props.sortdescending(key);
}
}
Is there any way to do this ? thanks.
You should have different state for individual components.
// Parent Component
import React from "react";
import SortDataFunc from "./SortDataFunc";
class SortData extends React.Component {
constructor() {
super();
this.state = { toggle: [true, true] };
this.handleClick = this.handleClick.bind(this);
}
handleClick(index) {
this.setState(state => {
return (state.toggle[index] = !state.toggle[index]);
});
}
render() {
return (
<div>
<SortDataFunc
id="0"
handleClick={this.handleClick}
toggled={this.state.toggle[0]}
/>
<SortDataFunc
id="1"
handleClick={this.handleClick}
toggled={this.state.toggle[1]}
/>
</div>
);
}
}
export default SortData;
// Child Component
import React from "react";
const SortDataFunc = props => {
const clickHandler = () => {
props.handleClick(props.id);
};
return (
<div>
<i
className={`fa ${props.toggled ? "fa-angle-down" : "fa-angle-up"}`}
aria-hidden="true"
onClick={clickHandler}
/>
</div>
);
};
export default SortDataFunc;
Sorting
component has own state sort
.
class Sorting extends React.Componet {
constructor(props){
super(props)
this.state = {sort:'ascending'}
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler(){
let sort = this.state.sort === 'ascending' ? 'descending' : 'ascending';
this.setState({
sort
})
this.props.sortData(this.props.type, sort);
}
render(){
return (
<span className="d-inline-flex">
<i className={`fa fa-angle-${this.state.sort === 'ascending' ? 'down' : 'up'}`} aria-hidden="true" onClick={this.clickHandler}></i>
)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.