fgonzalez fgonzalez - 6 months ago 25
Javascript Question

Adding/removing css classes to react components

I have a react component for pagination called 'Pager', depending on the number of results and the size of the page it calculates the number of pages to display, and then, when clicking on a link, it fetchs the results for that page. In my case, I'm having problem on adding/removing the css class dinamically when a user click on a link. When the page is rendered the first time only the number '1' has to be 'active', but then when the user clicks on the link '2', '3', etc I need to remove the className attribute for the previous active link and add it to the clicked link.

Any ideas on how to achieve that?

My code looks like:

export class Pager extends React.Component {


constructor() {
super();
}


handleClick(i){
console.log('Clicked on'+i);
this.props.dispatch(modelActionsCreator.findModelsByProductType(this.props.productType,i));
}

render() {
console.log(this.props.numPages);
let links = [];


for (let i = 1; i <= this.props.numPages; i++) {
links.push(<li key={i} className={i==1?'active':''}><a href="#" onClick={(e)=>{
e.preventDefault();
this.handleClick(i);
}}>{i}</a></li>);
}


return (<ul className="pagination">
<li className="prev-page"><a className="icon-arrow-left" href="#"></a></li>
{
links.map((item)=> {
return item;
})
}
<li className="next-page"><a className="icon-arrow-right" href="#"></a></li>
</ul>);


}

Answer

Put the active link in the component state. Something like:

export class Pager extends React.Component {

constructor() {
    super();
    this.state={
      i:1
    }
}


handleClick(i){
    console.log('Clicked on'+i);
    this.props.dispatch(modelActionsCreator.findModelsByProductType(this.props.productType,i));
    this.setState({i:i});
}

render() {
    console.log(this.props.numPages);
    let links = [];


    for (let i = 1; i <= this.props.numPages; i++) {
        links.push(<li key={i} className={i==this.state.i?'active':''}><a href="#" onClick={(e)=>{
        e.preventDefault();
        this.handleClick(i);
        }}>{i}</a></li>);
    }


    return (<ul className="pagination">
        <li className="prev-page"><a className="icon-arrow-left" href="#"></a></li>
        {
            links.map((item)=> {
                return item;
            })
        }
        <li className="next-page"><a className="icon-arrow-right" href="#"></a></li>
    </ul>);


}