Notice
Recent Posts
Recent Comments
Link
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

[react-project] input box 초기화 본문

Project

[react-project] input box 초기화

보람- 2023. 12. 29. 10:28

** 프로젝트 내용중에 검색하는 searchBar와 팔로우 유저와 채팅하는 input box가 있었다.

- 검색한 다음, 채팅의 메세지를 보낸 다음 입력내용이 사라지지않아서 초기화 작업을 해주었다!

 

1. searchBar 컴포넌트

- 검색한 내용을 서버에 요청보내야 했기 때문에 searchQuery로 상태를 관리하고있었고

- useEffect를 사용하여 setSearchQuery("")를 주어 검색창의 입력상태를 초기화했다.

 

const SearchBar = ({ handleSearch }) => {
  const location = useLocation();
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    setSearchQuery("");
  }, [location.pathname]);

  const handleSubmit = (e) => {
    e.preventDefault();
    handleSearch(searchQuery);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        required
        onChange={(e) => setSearchQuery(e.target.value)}
        type="text"
        placeholder={"Search..."}
        value={searchQuery}
      />
      <button>
        <img src={Search_icon} alt="" />
      </button>
    </form>
  );
};

 

 

 

 

2. chatting 컴포넌트

- searchBar와 같은 input box에 메세지를 입력하는 것은 맞지만 작성한 내용으로 상태를 관리하고 있지않아서 

- 입력한 값을 상태에 넣어 setInputValue("") 초기화 시켜주었다.

 

const Chatting = ({ roomId, nickname, image }) => {
  const [inputValue, setInputValue] = useState("");

  const sendMessage = () => {
    socket.emit("send-message", {
      user: {
        id: user.id,
      },
      content: inputValue,
    });
    setChat({
      user: {
        id: user.id,
      },
      content: inputValue,
    });
    setInputValue("");
  };

  return (
    <div>
      <div>
        <div>
          <div>
            <img src={image} className="w-[50px] h-[50px] rounded-3xl" alt="" />
          </div>
          <div>{nickname}</div>
        </div>
        <div>
          <div ref={chatRef}></div>
          <input
            placeholder="chat..."
            ref={inputRef}
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                sendMessage();
              }
            }}          
          />
        </div>
      </div>
    </div>
  );
};

 

 


※ 위의 코드는 스타일지우고 input box 초기화하는 방법에만 맞춘 코드입니다.