Home > OS >  move between two div with tow button using reactjs
move between two div with tow button using reactjs

Time:04-25

enter image description hereenter image description hereI need some help in the react js project: I have two div in react component, I want to switch between them using two buttons. When you press the first button, the first div appears and the second disappears and the opposite is also true. If possible, please explain it with a simple example, and thank you.

CodePudding user response:

It must be very simple and you can get it by a state variable that will control your buttons.

const [option, setOption] = useState('1');

This state variable option will hold 1 or 2 and if 1 is selected then it will show the first content part, otherwise 2nd content part will be shown.

And onClick on these options will change the state variable.

onClick={(e) => setOption('1')}

Here is a code. Code on sandbox

import React, {useState} from 'react';

import "./styles.css";

export default function App() {
  const [option, setOption] = useState('1');
  return (
    <div className="App">
      <div className="option-wrap">
        <div className={`option ${option === '1'? 'selected' : ''}`} onClick={(e) => setOption('1')}>Option 1</div>
        <div className={`option ${option === '2'? 'selected' : ''}`} onClick={(e) => setOption('2')}>Option 2</div>
      </div>
      <div className="content-wrap">
        {option === '1' && <div>Option 1 content</div>}
        {option === '2' && <div>Option 2 content</div>}
      </div>
    </div>
  );
}

Simple CSS


.option-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
}

.option-wrap .option {
  background: white;
  padding: 8px 12px;
  margin: 10px 12px 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
}

.option-wrap .option.selected {
  background: red;
  color: white;
}

  • Related