I am attempting to show a certain div when the relative li is selected. If any other divs are showing, I need to hide that one and only display the new one. There 1000% is a way more efficient way to do this then creating many useStates.
import {useState} from 'react'
import './dope.css'
export const PageContent = () => {
const [one, setOne] = useState('false')
const [two, setTwo] = useState('false')
function toggle1(){
set1(!1)
}
function toggle2(){
set2(!2)
}
return (
<section>
<div className='middle_wrapper'>
<div className='left_menu_wrapper'>
<nav className='nav_black'>
<li><a href='#!' onClick={toggle1}>1</a></li>
<li><a href='#!' onClick={toggle2}>2</a></li>
<li><a href='#!'>3</a></li>
<li><a href='#!'>4</a></li>
<li><a href='#!'>5</a></li>
<li><a href='#!'>6</a></li>
<li><a href='#!'>7</a></li>
<li><a href='#!'>8</a></li>
<li><a href='#!'>9</a></li>
<li className='no_border'><a href='/'>10</a></li>
</nav>
</div>
<div className='right_content'>
<section className='full_page'>
<div id='new_res' className={one? 'inactive' : 'active'}>
<h1>This is a 1 test</h1>
</div>
<div id='all_res' className={two? 'inactive' : 'active'}>
<h1>This is a 2 test</h1>
</div>
</section>
</div>
</div>
</section>
)
}
---- From dope.css ----
.active {
display: block;
}
.inactive {
display: none;
}
--------
https://gyazo.com/1838ccf473832a00f341f4366b97b670
Like above, I would like to make this more efficient, it's probably something very simple that I am overlooking because I am tired and need sleep. I think I could simply just toggle the div's using href='#new_res' but how would I keep it hidden if it's not in use?
Any help would be appreciated, I know this is something simple and I by time someone answers, I may have found the solution. If not, thank you for helping!
CodePudding user response:
If possible, it would be more efficient to simply use a checkbox.
However, if you have to use React state for flexibility, you could make a state with an array instead:
const [checkedArray, setCheckedArray] = useState([])
Whenever there is a new div to check toggle state, push a false
into the array, when it is clicked, turn it to be true:
// Example
// Adding new state
setCheckedArray((current)=>[...current,false])
// Mutating 3rd item's state
setCheckedArray((current)=>{
const newArray = [...current];
newArray[3] = true;
return newArray
})
// Getting the info of the 3rd item of the array
const stateOfThirdItem = checkedArray[3]
CodePudding user response:
Create a state to store all the components and their visibility flag. This will allow you to loop through them to dynamically render the anchors (and their onClick
event) and also show them in the DOM.
https://codesandbox.io/s/so-71716290-bdsp9w?file=/src/PageContent.js