Toggle between divs in React JSX

Viewed 1227

So I've got two input boxes that I want to be able to toggle (hide) between by clicking on them. They populate a table below them. I know it's not difficult but can't seem to make it happen easily.

It's all happening in the one component. Something like this:

<p id="toggle">
  <span> Employer </span>
  <span> Location </span>
</p>

<div id="left">..input box 1</div>
<div id="right">..input box 2</div>

What's the function I'd need to implement it? Thanks!

2 Answers

Your issue is indeed not very difficult. Here is a solution with a function component:

const MyComponent = (props) => {
    const [selected, setSelected] = useState(0)

    return (
        <div>
            <p id="toggle">
                <span onClick={() => setSelected(0)}> Employer </span>
                <span onClick={() => setSelected(1)}> Location </span>     
            </p>

            {(selected === 0) && <div id="left"> ..input box 1</div>}
            {(selected === 1) && <div id="right"> ..input box 2</div>}
        </div>
    )
}

Here is a solution with a class component:

class MyComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            selected: 0
        }
    }

    render() {
        return (
            <div>
                <p id="toggle">
                    <span onClick={() => this.setState({ selected: 0 })}> Employer </span>
                    <span onClick={() => this.setState({ selected: 1 })}> Location </span>     
                </p>

                {(selected === 0) && <div id="left"> ..input box 1</div>}
                {(selected === 1) && <div id="right"> ..input box 2</div>}
            </div>
        )
    }
}

If I'm understanding you're wanting to toggle the display of the div elemements on clicking the span elements (why not use anchors they're better suited). Below is a simple way to implement this,

(() =>
{
  const togglers = document.querySelectorAll('#toggle span');
  const togglees = document.querySelector('#toggle').parentNode.querySelectorAll('div');
  
  togglers.forEach((toggler, index) =>
  {
    toggler.addEventListener('click', () =>
    {
      togglees.forEach(togglee => togglee.style.display = 'none');
      togglees[index].style.display = 'block';
    }, true);
  });
})();
/* HIDE THOSE TOGGLEES BY DEFAULT CHANGE THIS!!!!!!!! */
div > div
{
  display: none;
}
<div>
  <p id="toggle">
    <span> Employer </span>
    <span> Location </span>     
  </p>

  <div id="left"> ..input box 1</div>
  <div id="right"> ..input box 2</div>
</div>

Related