//App.js
const App = () => {
const [inputStatus, setInputStatus] = useState('');
const handleClickButton = buttonName => {
setInputStatus(buttonName);
};
return (
<RadioWrapper>
<Radio
handleClickAdmin={handleClickButton}
click={inputStatus === 'first'}
text="first"
id="first"
/>
<Radio
handleClickAdmin={handleClickButton}
click={inputStatus === 'second'}
text="second"
id="second"
/>
<Radio
handleClickAdmin={handleClickButton}
click={inputStatus === 'third'}
text="third"
id="third"
/>
</RadioWrapper>
)};
//style-component
const RadioWrapper = styled.div`
display: flex;
justify-content: right;
padding-top: 11px;
margin-left: 155px;
`;
//컴포넌트.js
const Radio = props => {
const { handleClickAdmin, click, text, id } = props;
console.log('id->', id);
return (
<ButtonBox>
<AdminText>
<NomalImg
onClick={() => handleClickAdmin(id)}
alt="nomalImg"
src="/images/비활성화.png"
show={click}
/>
<ChangedImg
onClick={() => handleClickAdmin(id)}
alt="changedImg"
src="/images/활성화.png"
show={click}
/>
{text}
</AdminText>
</ButtonBox>
);
};
export default Radio;
const ButtonBox = styled.div`
display: flex;
justify-content: center;
margin-top: 10px;
margin-bottom: 20px;
`;
const AdminText = styled.div`
display: flex;
align-items: center;
margin-right: 30px;
font-weight: 800;
font-size: 14px;
line-height: 18px;
`;
const ChangeImg = styled.img`
margin: 0 8px 0 0;
width: 20px;
height: 20px;
background-color: white;
`;
const NomalImg = styled(ChangeImg)`
${({ show }) => {
return show ? `display:none` : `display:block`;
}}
`;
const ChangedImg = styled(ChangeImg)`
${({ show }) => {
return show ? `display:block` : `display:none`;
}}
`;
처음엔 input radio 타입의 버튼으로 코드를 짰다.
backgroun-color가 바뀌는 방법으로 로직을 짜니까 클릭시 흰배경 없이 전체색상이 바껴서 다른 방법을 생각했다.
디자인의 이미지를 따와서 클릭시 이미지를 뜨게 하는방법을 실행하려고 해봤지만 어려웠고, 비활성화 버튼과 활성화 이미지의 크기가 안맞았다.
그래서 그냥 둘다 이미지로 하기를 결심했다.
두개의 버튼일때는 state가 true/false로 실행했었는데,
세개일때는 동일하게 실행하면 셋중 하나를 클릭시 두개가 활성화됐다 결국 이것도 패스.
그래서 input radio버튼에서 checked로 클릭하는 방법을 생각했다.
checked 자리에 자식으로 넘겨주는 click
에 조건문을 달아줬고 onClick시 실행되는 함수에 props로 받아온 id
를 적어줬다.
뭐가됐던 당연히 안될줄 알았는데 한번에 성공했다.
이걸로 3일을 끙끙 앓았는데 결국엔 해냈다!
...엔돌핀이 돈다...ㅎ..ㅎ