28
loading...
This website collects cookies to deliver better user experience
npx create-react-app my-app
, npm init react-app my-app
, yarn create react-app
import { forwardRef} from "react";
export const InputNumber = forwardRef((props, ref) => {
return (
<input type="number" ref={ref} />
);
});
import { useState, forwardRef, useImperativeHandle } from "react";
import "./style.css";
export const InputNumber = forwardRef((props, ref) => {
const [state, setState] = useState(0);
const increment = () => {
setState((prev) => prev + 1);
};
const decrement = () => {
setState((prev) => {
if (prev === 0) {
return prev;
}
return prev - 1;
});
};
useImperativeHandle(ref, () => ({
inputValue: state,
}));
return (
<div className="input">
<span className="input-left" onClick={decrement}>
-
</span>
<span>{state}</span>
<span className="input-right" onClick={increment}>
+
</span>
</div>
);
});
import { useRef } from "react";
import "./App.css";
import { InputNumber } from "./InputNumber";
function App() {
const inputRef = useRef();
const addToCartHandler= () => {
const noOfCartItems = inputRef.current.inputValue;
alert("you have " + noOfCartItems + "item(s) in the cart");
};
return (
<div className="App">
<InputNumber ref={inputRef} />
<button onClick={addToCartHandler}>Add to Cart</button>
</div>
);
}
export default App;
.input {
background: #d36666;
border-color: #d36666;
position: relative;
cursor: default;
padding: 10px 30px;
color: #fafafa;
width: 50px;
margin: 15px 0;
}
.input-left,
.input-right {
position: absolute;
top: 0;
padding: 2.5px;
cursor: pointer;
height: 100%;
display: inline-flex;
align-items: center;
justify-content: center;
}
.input-left {
left: 5px;
}
.input-right {
right: 2.5px;
}