Adel
Adel

Reputation: 3733

ReactJS - Toggle two list in the state

I have two list in the state:

this.state = {
  fisrtList: [],
  secondList: [],
}

what I want is to toggle these lists, I mean:

const tmp = [];
tmp = fisrtList;
fisrtList = secondList;
secondList = tmp;

Since set state causes a render, this doesn't work. It just change one of them. I have used different approach like keeping the tmp in the state, but it also didn't work.

Do you have any recommendation for toggling these two list correctly?

Upvotes: 0

Views: 360

Answers (2)

Ori Drori
Ori Drori

Reputation: 191936

Set a new state with switched references. Since we are changing the references, there is no need to clone them.

Note: I'm using the updater callback option of setState.

this.setState(({ fisrtList, secondList }) => ({
  fisrtList: secondList,
  secondList: fisrtList
}));

Demo:

class App extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      fisrtList: [1, 2, 3],
      secondList: ['a', 'b', 'c']
    };
  }
 
  toggle = () => this.setState(({ fisrtList, secondList }) => ({
    fisrtList: secondList,
    secondList: fisrtList
  }));
  
  render() {
    const { fisrtList, secondList } = this.state;
    
    return (
      <div>
        <button onClick={this.toggle}>Toggle</button>
      
        <div>{fisrtList.join(',')}</div>
        
        <div>{secondList.join(',')}</div>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  demo
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>

Upvotes: 3

linasmnew
linasmnew

Reputation: 3977

Make a toggle method that looks like this:

toggle = () => {
   this.setState({
       fisrtList: this.state.secondList,
       secondList: this.state.fisrtList
    });
}

render() {
   return <button onClick={this.toggle}>Toggle the lists</button>
}

Upvotes: 0

Related Questions