I am trying to create a react component that represents a tile.
This component is just a div that's composed of a label and a checkbox.
The problem that I have is that I can click wherever on the component and the states changes like it would normally do (eg: by clicking on the component i can check or uncheck the checkbox). but when I click on the checkbox nothing happens.
Here is my newly created component code:
const Tile = ({ title }) => {
const [selected, setSelected] = useState(false);
useEffect(()=>{
console.log(selected)
},[selected])
return (
<>
<div className="tile" onClick={ev=>setSelected(curr=>!curr)}>
<label>{title}</label>
<input
type="checkbox"
checked={!!selected}
onChange={ev=>{setSelected(curr=>!curr)}}
></input>
</div>
</>
);
};
and here I use it in my App.js :
return (
<Container>
<Row>
<Col md={4}>
<Tile title="USA"></Tile>
<Tile title="MOROCCO"></Tile>
<Tile title="FRANCE"></Tile>
</Col>
<Col md={8}>
<h1>Hello</h1>
</Col>
</Row>
</Container>
and finally here is my css :
body {
padding-top: 20px;
font-family: "Poppins", sans-serif;
background-color: cornsilk;
}
.tile {
position: relative;
display: block;
width: 100%;
min-height: fit-content;
background: bisque;
padding: 8px;
margin: 1px;
}
.tile input[type="checkbox"] {
position: absolute;
top: 50%;
right: 0%;
transform: translate(-50%, -50%);
}
EDIT: the problem with using the htmlFor fix on the label is that the label is clickable and the checkbox is clickable but the space between them is not. I want the the whole component to be clickable
Aucun commentaire:
Enregistrer un commentaire