Answer the question
In order to leave comments, you need to log in
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} />
});
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>
);
}
Answer the question
In order to leave comments, you need to log in
Do I need to somehow take the id of the last element and add 1 to it?Yes.
let maxId = 0;
props.articles.forEach((article) => maxId = article.id > maxId ? article.id : maxId);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question