• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

109
Views
Cant remove specific React components

This is my Add_Blog.js file

import React, { useState } from "react";


function AddBlogs() {

const ADD = () => {
    return (
        <div>
            <label>Topic</label>
            <input></input>
            <label>Content</label>
            <textarea></textarea>
            <button type="button" onClick={deleteContent} value={state.length}> Delete</button>
        </div>
    );
}
const [state, setState] = useState([<ADD key="first"></ADD>]);


const addblog = () => {
    setState([...state, <ADD key={state.length}></ADD>])
}


const deleteContent = (event, key) => {
    setState([...state, state.splice(event.target.value, 1)]);

}

return (
    <div>
        <form>
            <div>
                <label>Add Title</label>
                <input></input>
            </div>
            <div>
                {
                    state
                }

            </div>
            <div>
                <button type="button" onClick={addblog}>Add another topic</button>
            </div>
            <input type="submit" value="publish"></input>
        </form>
    </div>
);
}
export default AddBlogs;

My expectation from this code is to remove component left of delete button when I press that delete button. But when I press delete button it removes that component and every components below it. Any solution for this?

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It does not work because you are using the splice method wrong. It returns the deleted value.

You can change your deleteContent function like this:

const deleteContent = (event, key) => {
  let indexToRemove = Number(event.target.value);
  setState((prevState) => prevState.filter((elem, index) => index !== indexToRemove));
}

That will be enough for the program to work as expected

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error