As a React beginner exercice I have a component checkbox for a list of devices. If a device is checked, I want my App parent element to display the name of the device. I tried several ways to do it but cannot achieve it. Here is my code
Checkbox.jsx
import { useState, useEffect } from "react"
const Checkbox = ({ label, name, sendData}) => {
const [isChecked, setIsChecked] = useState(false);
const handleChange =() => {
setIsChecked({isChecked: !isChecked} )
}
useEffect(()=> {
sendData(isChecked)
})
return (
<div className="checkbox-wrapper">
<label>
<input
type="checkbox"
checked={isChecked }
onChange={handleChange}
name={name}
/>
<span>{label}</span>
</label>
</div>
);
};
export default Checkbox;
App.js
import { useState } from 'react';
import Checkbox from './components/Checkbox'; import './App.css';
import { useState } from 'react';
import Checkbox from './components/Checkbox';
import './App.css';
function App() {
const [ownDevice, setOwnDevice] = useState(false)
const sendData = (childData) => {
setOwnDevice(childData)
}
const displayDevice = (Checkbox) => {
if (ownDevice) {
return Checkbox.name
}
}
return(
<div className="App">
<h1>What devices do you own?</h1>
<Checkbox label="laptop" name="laptop" sendData={sendData} />
<Checkbox label="desktop" name="desktop" />
<Checkbox label="phone" name="phone" />
<p>{displayDevice}</p>
</div>
)
}
export default App;
Aucun commentaire:
Enregistrer un commentaire