A
A
Aristotel Paskalov2021-11-10 13:59:52
React
Aristotel Paskalov, 2021-11-10 13:59:52

How to set id to new array elements?

In one of the components, I use the .map() method to display the articles in the application:

const articlesList = props.articles.map(article => {
        return <Article article={article} key={article.id} />
    });


Also in the application there is a form with which you can add a new article:

export default props => {

    const [articleTitle, setArticleTitle] = useState('');
    const [articleText, setArticleText] = useState('');

    const handleInput = event => {
        if (event.target.name === 'article-title') {
            setArticleTitle(event.target.value);
        } else {
            setArticleText(event.target.value);
        }
    };

    const handleSubmit = event => {
        event.preventDefault();
        props.addArticle({ id: Date.now(), title: articleTitle, text: articleText });
        setArticleTitle('');
        setArticleText('');
    }

    return (
        <div className="admin">
            <form className="article__form" onSubmit={handleSubmit}>
                <label htmlFor="article__title">Название статьи</label>
                <input type="text" value={articleTitle} onChange={handleInput} id="article__title" name="article-title"
                       placeholder="Введите название статьи"/>
                <label htmlFor="article__text">Текст статьи</label>
                <textarea type="text" value={articleText} onChange={handleInput} id="article__text" name="article-text"
                          placeholder="Введите текст статьи"/>
                <button type="Submit">Добавить</button>
            </form>
        </div>
    );
}


In the handleSubmit function, I need to create a new article object, but I don't know how to specify an id for it. Therefore temporarily wrote Date.now ()

How it is possible to specify id for this element?

For example, if the last article has id 3, then in order for the element we create to have id 4
Do we need to somehow take the id of the last element and add 1 to it?

Tell me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-11-10
@iNeextt

Do I need to somehow take the id of the last element and add 1 to it?
Yes.
The map method has nothing to do with it, the form is rendered outside of it. Add a prop to the form component, in which from the parent pass just "id of the last element + 1".
You can get the id of the last element in a bunch of ways, here is one of them for an example:
let maxId = 0;
props.articles.forEach((article) => maxId = article.id > maxId ? article.id : maxId);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question