This could potentially be a very basic question, but I'm trying to figure out how to move a div when a user clicks a button. In my case, I want a white bar at the bottom of a page to move downwards when a user clicks the button.
const [movepos, setMovepos] = useState("0")
return (
<>
<div style={{
position: "absolute",
width: "100%",
height: "60px",
bottom: {movepos},
zIndex: "10000000000",
boxShadow: "box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px",
backgroundColor: "white"
}} className="media-player-bar"></div>
<button onClick={() => setMovepos(movepos==="0" ? "-60px" : "0")}className="test-button">Click me</button>
</>
)
When setting 0 or -60px for bottom it's in the right position, but when I do it this way it just positions it at the top and the button does nothing. Is there another way of achieving what I want, or am I missing something?
CodePudding user response:
There are many ways to get the wanted result, i will show two of them here:
- make your parent element 'position: relative', and then create a state for the 'top' style like this:
const [style, setStyle] = useState('top: 0px')
add click for the button like this:<button onClick={() => setStyle('top: '100px')/>Click me</button>
. now pass the style to your bar element:<YourBar style={style}/>
this will move the element but can break the UI's page. so you will have to play with it a bit, maybe making your element position: absolute;
- have two same elements and render only one of them when needed like this:
create a state for the element flag:
const [showTop, setShowTop] = useState(true);
and do like this: `
<div>
<button onClick={() => setTop(false)}>Click Me</button>
{showTop && <YourBar />}
...
{!showTop && <YourBar />
</div>`
by that you can make sure it will be positioned in right place and wont break UI.
worth mentioning, by removing an element from DOM, it will remove its height too and page will go top the same amount as the element that was removed. if you wish to keep the height of the element, use css for visability/opacity or wrap your bar with a div and set the height you want and just hide the bar itself inside it.