I want to change height size of div elements "Container-2". So, when i click button components and got value = 10, height of "Container-2" will change to 100px, previous is 50px.
App.js
import React from 'react';
import Tugas9 from './tugas9/tugas9';
const App = () => {
return (
<>
<Tugas9/>
</>
);
}
export default App;
tugas9.js
import React from "react";
import { useState } from "react";
import './Tugas9.css';
function Tugas9 () {
const [angka, setAngka] = useState(1);
const increment = () => {
setAngka(angka 1);
}
return (
<div className="Container-2">
<div className="App-2">
<p>{angka}</p>
<button onClick={increment}>Tambah</button>
{angka >= 10 ? <span>State count sudah lebih dari 10!!</span> : null}
</div>
</div>
)
}
export default Tugas9;
CSS
.Container-2 {
width: 800px;
height: 50px;
border-radius: 8px;
box-shadow: 3px 3px 7px 0px rgba(0,0,0,0.5);
-webkit-box-shadow: 3px 3px 7px 0px rgba(0,0,0,0.5);
-moz-box-shadow: 3px 3px 7px 0px rgba(0,0,0,0.5);
margin: auto;
margin-top: 100px;
padding: 30px;
}
.App-2 p {
margin-top: 0;
text-align: center;
}
.App-2 button {
padding: 5px 375px;
margin: 0 auto;
}
.App-2 span {
display: block;
margin-top: 10px;
}
I've tried many ways, but still didn't work. I'm also a beginner with React JS :)
CodePudding user response:
Have you heard about the useEffect()
hook? It allows you to respond to the changes of state in your app.
Here's how it could solve your problem. First, you define the height of the box as a state:
const [boxHeight, setBoxHeight] = useState(50)
and then use inline styling to define the height of the box:
<div className="Container-2" style={{height: `${boxHeight}px`}}>
...
Now, the last thing we need to do is to change the height whenever angka
state is more than 10
. Let's use the useEffect()
hook to achieve it:
useEffect(() => {
if (angka >= 10) {
setBoxHeight(100)
}
}, [angka])
If you're not familiar with the useEffect()
hook, make sure to read the official docs.