본문 바로가기

언어공부-프론드엔드/JSX,React

TIL)노마드코더 React hooks

useInput (유효성 검사 포함)

import { useState } from "react";
import "./styles.css";
// useInput
export const useInput = (initialValue,validator) => {
  const [value, setValue] = useState(initialValue);
  const onChange = (event) => {
    const value = event.target.value;
    let will =true;
    if (typeof validator === "function") {
      will = validator(value)
    }
    if (will) {
      setValue(value)
    }
  } 
  return {
    value,onChange
  };
};

export default function App() {
  const maxLen = (value) => value.length <10;
  const name = useInput("Mr.",maxLen);
  return (
    <div className="App">
      <h2>Start editing to see some magic happen!</h2>
      <input placeholder="name" {...name}/> 
      {/* {...name} name안에 있는 모든 것을 보여준다. */}
    </div>
  );
}

 

useTabs

*오류

React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
==위와 같은 에러가 떴을 때 아래와 같이 useState()를 최상단으로 이동시켜주시면 됩니다.
*최상위(at the Top Level)에서만 Hook을 호출해야 합니다.
import { useState } from "react";
import "./styles.css";
//useTabs
const content = [{tab : "a", content: "b"},{tab : "a2", content: "b2"}]
const useTabs = (initaialTab, all) => {
  //
  const [current,setCurrent] = useState(initaialTab)
  //Array.isArray()는 해당인자가 array인지 알려준다.
  //해당 조건문은 배열이 아닐때 리턴하는 조건이다.
  if(!all || !Array.isArray(all)) {
    return;
  }

return {currentItem : all[current] , changeItem : setCurrent}
}
export default function App() {
  //content가 배열이여서 기본을 0값으로
  const {currentItem,changeItem} = useTabs(0,content)
  return (
    <div className="App">
      <h2>Start editing to see some magic happen!</h2>
      {content.map((item, index) => (<button onClick={()=>changeItem(index)}>{item.tab}</button>))}
    <div>{currentItem.content}</div>
    </div>
  );
}