반응형

React 검색 기능 만들기

 

App.js

import { useEffect, useState } from "react";


const App = () => {

    const array = [
        {
            id: 0,
            title: '안녕',
            nick: 'shiro21'
        },
        {
            id: 1,
            title: '하세요',
            nick: 'asd'
        },
        {
            id: 2,
            title: '안녕히',
            nick: 'aaa'
        },
        {
            id: 3,
            title: '가세요',
            nick: 'bbb'
        },
    ];

    const [contents, setContents] = useState(array);
    const [search, setSearch] = useState('');

    useEffect(() => {
        const filter = array.filter((item) => {
            return item.title.toUpperCase().includes(search.toUpperCase());
        });

        setContents(filter);
        
    }, [search]);

    const titleChange = (e) => {
        setSearch(e.target.value);
    };
    console.log(contents);
    console.log(search);


    return (
        <>
            <input type="text" value={search} placeholder="타이틀을 입력해주세요." onChange={titleChange} />
        </>
    );
};


export default App;

위 코드는 includes함수로 배열에서 특정값을 포함하고 있는지 확인하고, filter() 메서드로 포함하고 있는 지정된 배열의 요소로 얕은 복사를 만들어줍니다.

:: toUpperCase() 메서드로 소문자를 대문자로 변환해서 소문자 대문자를 구분하지 않도록 해줍니다.

반응형

+ Recent posts