찍어내기/반복 : 함수화
useState /useEffect 반복 : 커스텀 훅
<!DOCTYPE html>
<html lang="en">
<body>
<script
crossorigin
src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
const rootElement = document.getElementById("root");
function useLocalStorage(itemName, value =""){
const [state,setState] = React.useState( () =>{
return window.localStorage.getItem(itemName) || value;
});
React.useEffect(()=>{
window.localStorage.setItem(itemName, state);
},[state]);
return [state,setState];
}
const App = () => {
const [keyword,setkeyword] = useLocalStorage("keyword");
const [result,setResult] = useLocalStorage("result");
const [typing,setTyping] = useLocalStorage("typing", false);
function handleChange(event){
setkeyword(event.target.value);
setTyping(true);
}
function handleClick(event){
setTyping(false);
setResult(`We find results of ${keyword}`)
}
return (
<>
<input onChange={handleChange} value={keyword}/>
<button onClick={handleClick}>search</button>
<p>
{typing ? `Looking for ...${keyword}` : result}
</p>
</>
)
}
ReactDOM.render(<App />,rootElement);
</script>
</body>
</html>