开发者

Custom hook to add items into a todo list

I would highly appreciate advice regarding my custom hook. the hook performs the functionality I'm expecting it to perform however I'm not sure that I'm utilizing the best practices of React or whether my code can be improved.

thanks in advance!

useAddItem (custom hook):

import { useRef, useState, useEffect } from 'react';

export const useAddItem = (refItem) => {
    const [list, setList] = useState([]);

    const adddingItem = e => {
        if (e.which === 13 && e.target.value.length > 0) {
            console.log(e);
            setList(prev => [...prev, e.target.value]);  
        };
    };

    // Cleari开发者_高级运维ng the input field after submition, not sure that this is the correct way
    useEffect(() => {
        refItem.current.value = "";
    }, [list]);

    return [list, adddingItem];
};

todo list page component:

import { NextFunctionComponent } from 'next';
import Image from 'next/image';
import styles from "./list_items_index.module.scss";
import { useAddItem } from 'hooks/useAddItem';
import { useRef } from 'react';

export const ListItems : NextFunctionComponent = ({theme}) => {
    const inputRef = useRef(null);
    const [list, adddingItem] = useAddItem(inputRef);
    
    return (
        <div className={styles["list-items"]} data-theme={theme} data-testid="list-items">
            <input ref={inputRef} className={styles["list-items_input"]} type="text" onKeyPress={(e) => adddingItem(e)} />
            <div className={styles["list-items_content"]}>
                <ul className={styles["list-items_content__list"]}>
                    {list.map((item, index) => {
                        return <li key={index}><span></span>{item}</li>
                    })}
                </ul>
                <div className={styles["list-items_footer"]}>
                    <p>items left</p>
                    <ul className={styles["list-items_filters"]}>
                        <li>All</li>
                        <li>Active</li>
                        <li>Completed</li>
                    </ul>
                    <p>Clear Completed</p>
                </div>
            </div>
        </div>
    );
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜