import React, { useState, StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";
const useInput = (initialValue) => {
const [value, setValue] = useState(initialValue);
const onChange = (event) => {
setValue(event.target.value);
};
return { value, onChange };
};
const App = () => {
const name = useInput("Name:");
return (
<div className="App">
<h1>Hello</h1>
<input placeholder="Name" {...name} />
{}
</div>
);
};
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>
);
- useInput을 이용하여 입력 검증기능 만들기
import React, { useState, StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";
const useInput = (initialValue, validator) => {
const [value, setValue] = useState(initialValue);
const onChange = (event) => {
const {
target: { value }
} = event;
let willUpdate = true;
if (typeof validator === "function") {
willUpdate = validator(value);
}
if (willUpdate) {
setValue(value);
}
};
return { value, onChange };
};
const App = () => {
const maxLength = (value) => value.length <= 10;
const name = useInput("Name:", maxLength);
return (
<div className="App">
<h1>Hello</h1>
<input placeholder="Name" {...name} />
{}
</div>
);
};
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>
);