Как создать Tags Project в React с исходным кодом

Сначала посмотрите, как будет выглядеть наш проект добавления тегов.

Итак, сначала мы сделаем NeceSarry Import.

  1. Компонент импортирует библиотеки React, useState, AddStyle.css и RxCross2.
import React, {useState} from "react";
import './AddStyle.css'
import {RxCross2} from 'react-icons/rx'

Также сделайте npm i react-icons

  1. Компонент определяет переменную состояния с именем tagText и инициализирует ее пустой строкой.
  2. Компонент определяет переменную состояния с именем tags и инициализирует ее пустым массивом.
  3. Компонент определяет функцию forceRender, которая вызывает повторную визуализацию компонента.
const [tagText,setTagText] = useState('');
    // This creates a state variable called `tagText` and initializes it to an empty string.

    const [tags,setTags] = useState([]);
    // This creates a state variable called `tags` and initializes it to an empty array.

    const [reRender,setReRender] = useState(false)
    // This creates a state variable called `reRender` and initializes it to `false`.

Итак, теперь наш код будет выглядеть так

import React, {useState} from "react";
import './AddStyle.css'
import {RxCross2} from 'react-icons/rx'

// This imports the React library, the `useState` hook, the `AddStyle.css` stylesheet, and the `RxCross2` icon from the `react-icons/rx` library.

const AddTags = () =>{
    // This is the function that renders the `AddTags` component.

    const [tagText,setTagText] = useState('');
    // This creates a state variable called `tagText` and initializes it to an empty string.

    const [tags,setTags] = useState([]);
    // This creates a state variable called `tags` and initializes it to an empty array.

    const [reRender,setReRender] = useState(false)
    // This creates a state variable called `reRender` and initializes it to `false`.

const forceRender = () =>{
        setReRender(!reRender)
    }
    // This function forces a re-render of the component.

return()
}
export default AddTags;

4. Компонент определяет функцию с именем handleAddTag, которая обрабатывает событие нажатия пользователем клавиши Enter, когда поле ввода находится в фокусе. Он очищает поле ввода и, если текст в поле не пуст, добавляет текст в массив tags.

    const handleAddTag = (e) =>{
        forceRender()
        if(e.key==='Enter'){
            setTagText('')
            if(tagText !== ''){
                setTags([...tags,tagText])
            }else{
                console.log('empty')
            }
        }
    }
    // This function handles the event of a user pressing the Enter key while the input field is focused. It clears the input field, and if the text in the field is not empty, it adds the text to the `tags` array.

5. Компонент определяет функцию с именем handleDeleteTag, которая обрабатывает событие, когда пользователь щелкает значок «x» рядом с тегом. Он удаляет тег из массива tags.

const handleDeleteTag = (index) =>{
        forceRender()
        tags.splice(index,1)
    }
    // This function handles the event of a user clicking on the "x" icon next to a tag. It removes the tag from the `tags` array.

6. Компонент возвращает элемент div со следующими дочерними элементами:

  • Элемент h5 с текстом «Добавить теги».
  • Элемент div с именем класса addTagInput, который содержит следующие дочерние элементы:

Элемент div с именем класса tags для каждого тега в массиве tags. Каждый элемент div содержит следующих дочерних элементов:

  • Элемент span с текстом тега
  • Элемент div с именем класса crossIcon, который содержит значок RxCross2. Этот значок используется для удаления тега.

Элемент input с именем класса inputTag, который используется для добавления тегов. Элемент ввода имеет следующие свойства:

  • autoFocus: Это свойство приводит к тому, что элемент ввода будет сфокусирован при рендеринге компонента.
  • value: это свойство связано с переменной состояния tagText.
  • onKeyUpCapture: Этот обработчик событий вызывается, когда пользователь нажимает клавишу в элементе ввода. Он вызывает функцию handleAddTag, если пользователь нажимает клавишу Enter.
  • onChange: Этот обработчик событий вызывается, когда пользователь изменяет текст в элементе ввода. Он вызывает функцию setTagText для обновления переменной состояния tagText.

Когда компонент визуализируется, он отображает список тегов. Пользователь может добавлять теги, вводя их в поле ввода и нажимая клавишу Enter. Пользователь может удалить теги, щелкнув значок «x» рядом с тегом.

return(
        <div className="AddTagContainer">
            <div className="addTagBox">
                <h5>Add Tags</h5>
                <div className="addTagInput">
                    {
                        tags.map((tag,index)=>{
                            return(
                                <div className="tags" key={index}>
                                    <span>{tag}</span>
                                    <div className="crossIcon" onClick={()=>handleDeleteTag(index)}>
                                        <RxCross2/>
                                        </div>
                                </div>
                            )
                        })
                    }
                    <input className="inputTag" type="text" autoFocus 
                        value={tagText}
                        onKeyUpCapture={(e)=>{handleAddTag(e)}}
                        onChange={(e)=>setTagText(e.target.value)} />
                </div>
            </div>
        </div>
    )

И, наконец, на этом мы закончили нашу реактивную часть кода. Итак, теперь наш окончательный код React будет выглядеть так.

import React, {useState} from "react";
import './AddStyle.css'
import {RxCross2} from 'react-icons/rx'

// This imports the React library, the `useState` hook, the `AddStyle.css` stylesheet, and the `RxCross2` icon from the `react-icons/rx` library.

const AddTags = () =>{
    // This is the function that renders the `AddTags` component.

    const [tagText,setTagText] = useState('');
    // This creates a state variable called `tagText` and initializes it to an empty string.

    const [tags,setTags] = useState([]);
    // This creates a state variable called `tags` and initializes it to an empty array.

    const [reRender,setReRender] = useState(false)
    // This creates a state variable called `reRender` and initializes it to `false`.

    const forceRender = () =>{
        setReRender(!reRender)
    }
    // This function forces a re-render of the component.

    const handleAddTag = (e) =>{
        forceRender()
        if(e.key==='Enter'){
            setTagText('')
            if(tagText !== ''){
                setTags([...tags,tagText])
            }else{
                console.log('empty')
            }
        }
    }
    // This function handles the event of a user pressing the Enter key while the input field is focused. It clears the input field, and if the text in the field is not empty, it adds the text to the `tags` array.

    const handleDeleteTag = (index) =>{
        forceRender()
        tags.splice(index,1)
    }
    // This function handles the event of a user clicking on the "x" icon next to a tag. It removes the tag from the `tags` array.

    return(
        <div className="AddTagContainer">
            <div className="addTagBox">
                <h5>Add Tags</h5>
                <div className="addTagInput">
                    {
                        tags.map((tag,index)=>{
                            return(
                                <div className="tags" key={index}>
                                    <span>{tag}</span>
                                    <div className="crossIcon" onClick={()=>handleDeleteTag(index)}>
                                        <RxCross2/>
                                        </div>
                                </div>
                            )
                        })
                    }
                    <input className="inputTag" type="text" autoFocus 
                        value={tagText}
                        onKeyUpCapture={(e)=>{handleAddTag(e)}}
                        onChange={(e)=>setTagText(e.target.value)} />
                </div>
            </div>
        </div>
    )
}
export default AddTags;

Теперь вывод будет выглядеть так без CSS

Теперь давайте добавим CSS в наш окончательный проект Addtags.

.AddTagContainer {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
  }


.addTagBox{
    width: 30rem;
    height: auto;
    background-color: white;
    border-radius: 15px;
    box-shadow: rgba(17, 12, 46, 0.15) 
    0px 48px 100px 0px;
    box-sizing: border-box;
    padding: 1rem;
    font-family: 'work sans', sans-serif;
    font-weight: 500;
}
.addTagBox > h5{
    margin: 0;
    color: black;
    font-size: 1rem;
}
.addTagInput{
    margin-top: 1rem;
    display: flex;
    grid-gap:10px;
    flex-wrap: wrap;
}
.inputTag{
    border: none;
    font: inherit;
    max-width: 6rem;
}
.inputTag:focus{
    outline: none;
}
.tags{
    background-color: #ECECF8;
    padding: 5px 10px;
    border-radius: 50px;
    display: flex;
    grid-gap: 5px;
    align-items: center;
}
.crossIcon{
    background-color: white;
    display: flex;
    align-items: center;
    border-radius: 50%;
    font-size: 1rem;
    padding: 2px;
    cursor: pointer;
}

И это все, что мы готовы с проектом, который вы видели в начале

А также Вы можете Вживую Проверить это здесь.



- -- - -- - - - - - - - - - - - Конец - - - - - - - - - - - - -

Если вам понравилось читать этот блог, поделитесь им с друзьями и не забудьте подписаться на наш канал YouTube, чтобы получать больше интересного контента. Помогите нам рассказать о нашем опыте в разработке стека MERN, облачных вычислениях, React Native и Next.js, и следите за новостями, чтобы не пропустить новые информативные статьи. Вместе мы можем покорить мир технологий!

В разделе Проекты Mern Stack вы можете найти учебные пособия, советы, шпаргалки и другие проекты. Наши доклады также касаются фреймворков React, таких как NextJs и AWS Cloud. Присоединяйтесь к нам сегодня, чтобы быть в курсе новейших технологий🩷

📠 🏅:- Проекты Mern Stack

🎦 🥇:- Дневник Джары — YouTube 🚦

🎦 🥈 :- Эррормания — YouTube 🚦

На GITHUB:- raj-28 (Raj) (github.com)

💌 Подпишитесь на нашу рассылку, чтобы быть в курсе всех новых блогов 👍

…………🚦…🛣… ……………🚧🛑………………..▶……………….️

Используйте смайлики отсюда, если вам нужны….🚦🛣️🥇🥈🥉🏅🎖️🎦👍