I made a month picker like the picture below. I erased the code, leaving only the part to ask questions. When the month picker is rendered for the first time, there is no selected value, and if I select month, the value comes out. I want to return false when nothing is selected at first and return true when month is selected. So I checked the value with console.log(
pickMonth:,pickMonth==="")
, and when it was rendered for the first time, true came out and false returned if there was a value. So I typed console.log(
pickMonth:,pickMonth===!"")
because I needed the opposite value. But whether there is a value or not, it keeps returning false. What's wrong? I'd appreciate it if you let me know thanks.
code:
import React, { useState } from 'react'
import styled from 'styled-components';
import Cake from '../resources/images/img/cake.png'
import DownArrow from '../resources/images/img/downarrow.png'
const BirthdayWrap = styled.div`
flex-direction: column;
display: flex;
position: relative;
z-index: 0;
`
function Birthday() {
const [pickMonth,setPickMonth] = useState('');
const handleSelectMonth = (e) => {
setPickMonth(e.target.value)
}
console.log(`pickMonth:`, pickMonth==='')
console.log(`pickMonth value:`, pickMonth)
return (
<BirthdayWrap isLoginGood={isLoginGood} pickMonth={pickMonth} pickDay={pickDay} pickYear={pickYear}>
<div>
<span>
<img alt='cake' src={Cake} />
</span>
<div>
<div>
<span>
<span>
<img alt='arrow' src={DownArrow} />
</span>
<select value={pickMonth} onChange={handleSelectMonth}>
<option className='monthOption' value="1">
Jan
</option>
<option className='monthOption' value="2">
Feb
</option>
<option className='monthOption' value="3">
March
</option>
</select>
</span>
<span>
<span>
<img alt='arrow' src={DownArrow} />
</span>
</span>
</div>
</div>
</div>
</BirthdayWrap>
)
}
export default Birthday;
CodePudding user response:
You should only have to use a double bang on pickMonth
instead of doing a comparison operator. Empty strings are inferred as falsey.
let pickMonth = ''
console.log(`pickMonth: `, !!pickMonth) // pickMonth: false
let pickMonth = 'foo'
console.log(`pickMonth: `, !!pickMonth) // pickMonth: true