79 lines
2.4 KiB
JavaScript
79 lines
2.4 KiB
JavaScript
import React,{Fragment,useState} from "react";
|
|
|
|
const CarComponent = () => {
|
|
const divStyle = {
|
|
padding: "10px",
|
|
margin: "10px"
|
|
};
|
|
|
|
const[datos, setDatos] = useState("");
|
|
const[cars, setCars] = useState([]);
|
|
|
|
const handleInputChange = (event) => {
|
|
setDatos({
|
|
...datos,
|
|
[event.target.name]: event.target.value
|
|
});
|
|
};
|
|
|
|
const addCar = () => {
|
|
let newCar = {
|
|
model: datos.model,
|
|
brand: datos.brand,
|
|
license: datos.license
|
|
};
|
|
|
|
if (!newCar.model || newCar.model.trim() === "") {
|
|
alert("Model cannot be left blank!");
|
|
}
|
|
else if (!newCar.brand || newCar.brand.trim() === "") {
|
|
alert("Brand cannot be left blank!");
|
|
}
|
|
else if (!newCar.license || newCar.license.trim() === "") {
|
|
alert("License plate cannot be left blank!");
|
|
}
|
|
else if (newCar.license.length !== 6) {
|
|
alert("License plates must contain 6 letters or numbers!");
|
|
}
|
|
else {
|
|
setCars(cars => [...cars, newCar]);
|
|
setDatos({
|
|
model: "",
|
|
brand: "",
|
|
license: ""
|
|
});
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Fragment>
|
|
<div align="center" style={divStyle}>
|
|
<div>
|
|
<h1>Add new car</h1>
|
|
</div>
|
|
<div style={divStyle}>
|
|
<input type="text" placeholder="Model" name="model" value={datos.model} onChange={handleInputChange}></input>
|
|
</div>
|
|
<div style={divStyle}>
|
|
<input type="text" placeholder="Brand" name="brand" value={datos.brand} onChange={handleInputChange}></input>
|
|
</div>
|
|
<div style={divStyle}>
|
|
<input type="text" placeholder="License plate" name="license" value={datos.license} onChange={handleInputChange}></input>
|
|
</div>
|
|
<div style={divStyle}>
|
|
<button onClick={addCar} value="send">Add</button>
|
|
</div>
|
|
</div>
|
|
<div align="center">
|
|
<div>
|
|
{cars.map((cars) => (
|
|
<li>{cars.model} {cars.brand} {cars.license}</li>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</Fragment>
|
|
);
|
|
};
|
|
|
|
export default CarComponent;
|