📌 배열의 각 아이템에 쉽고 빠르게 이름 붙이는 방법은 아래와 같습니다.
const food = ['tomato', 'potato']
const [firstFood, secondFood] = food;
// 아래와 같이 지정되어 나타납니다.
firstFood = 'tomato'
secondFood = 'potato'
📌 useState()를 사용하면 배열값을 반환해줍니다.
첫 번째 요소는 담고자 하는 data 값이고 두번째 요소는 data 값을 바꿀때 사용할 modifier입니다.
function App() {
const [counter, setCounter] = React.useState(0);
const onClick = () => {
//setCounter(counter + 1;);
setCounter((current) => current + 1);
};
return (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={onClick}>Click me</button>
</div>
);
}
📌 JSX에서 클래스 네임과 label에 for 속성을 사용해야할 경우 아래와 같이 작성해 주어야 합니다.
function App() {
return (
<div>
<h1 className='hi'>Super converter</h1> 📌 // className
<label htmlFor='minutes' >Minutes</label> 📌 // htmlFor
<input id='minutes' placeholder='Minutes' type='number' />
<label htmlFor='hours'>Hours</label>
<input id='hours' placeholder='Hours' type='number' />
</div>
);
}
📌 useState 를 활용하여 시간에서 분단위변경 분단위에서 시간 단위 변경 해주는 방법을 아래의 코드에서 확인할 수 있습니다.
function App() {
const [minutes, setMinutes] = React.useState(0); //default값 = 0
const [flipped, setFlipped] = React.useState(false);
const onChange = (event) => {
setMinutes(event.target.value);
};
const reset = () => setMinutes(0);
const onFlip = () => {
reset();
setFlipped((current) => !current); // 들어갈 값의 반대 값을 넣어줌
}
return (
<div>
<h1 className='hi'>Super converter</h1>
<div>
<label htmlFor='minutes' >Minutes</label>
<input
// 분단위 변환
value={flipped ? minutes * 60 : minutes}
id='minutes'
placeholder='Minutes'
type='number'
onChange={onChange}
disabled={flipped}
/>
</div>
<div>
<label htmlFor='hours'>Hours</label>
<input
// 시간단위 변환
value={flipped ? minutes : Math.round(minutes / 60)}
id='hours'
placeholder='Hours'
type='number'
disabled={!flipped}
onChange={onChange}
/>
</div>
<button onClick={reset}>Reset</button>
// 📌 버튼에 표시되는 글자도 변환해줄 수 있음
<button onClick={onFlip}>{flipped ? "turn back" : "flip"}</button>
</div>
);
}
const root = document.getElementById('root');
ReactDOM.render(<App />, root)
📌 select, option 태그와 useState 를 사용하여 선택 랜더링 해줄 수 있습니다. MinutesToHours 와 KmToMiles 함수가 있다는 가정하에 각 value 값에 맞는 option을 선택해주면 해당하는 내용만 화면에 출력됩니다.
function App() {
const [index, setIndex] = React.useState('xx'); //📌초기값
const onSelect = (event) => {
setIndex(event.target.value);
}
return (
<div>
<h1>Super converter</h1>
<select value={index} onChange={onSelect}> //📌
<option value='xx'>Select your units</option>
<option value='0'>Minutes & Hours</option>
<option value='1'>Km & Miles</option>
</select>
<hr />
{index === 'xx' ? 'Please select your units' : null }
{index === '0' ? <MinutesToHours /> : null }
{index === '1' ? <KmToMiles /> : null }
</div>
);
}
const root = document.getElementById('root');
ReactDOM.render(<App />, root)