N
N
NikolayIII2022-02-22 00:21:53
css
NikolayIII, 2022-02-22 00:21:53

React. How to remove created element from parent's state in child element?

Good afternoon. Please advise how to resolve this issue.

There is a parent element that stores an array of property elements in the state (initially it is empty). Adding properties occurs through a button in the parent element and a function.

const ConstructorPage = () => {
  const [property, setProperty] = useState([])
  
  const delProperty = () => {	
    //функция удаления созданного свойства из property
  }
  
  const addProperty = () => {
    const key = Math.random() * 100,
      newProperty = <Property key={key} obj={obj} forObj={forObj} delProperty={delProperty} />

    setProperty([...property, newProperty])
  }
  
  return (
    <> 
      <Button onClick={() => addProperty()}>Add</Button>
      
      {property}
    </>
  )
}


The child element accepts the delete function from the parent element and should call it on the button.

const Property = (props) => {
  return (
    <div>
      //необходимые данные
      <Button onClick={() => props.delProperty()}>Del</Button>
    </div>
  )
}


But it turns out that in each created property, the previous state of the property array is stored, and when the delete function is called, this Property element does not yet exist in the property array. How to make the delProperty function have access to the current state of the property, and not to the previous one?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yeah, 2016-04-01
@Yeah

Take a look at Swiper.js . Pretty powerful thing with a bunch of settings. Perhaps with its help you will be able to realize your plan.

0
0xD34F, 2022-02-22
@NikolayIII

const Property = ({ data, onDelete }) => (
  <div>
    #{data.id}
    <button onClick={onDelete}>Del</button>
  </div>
);

const ConstructorPage = () => {
  const [ properties, setProperties ] = useState([]);
  const delProperty = property => setProperties(properties.filter(n => n !== property));
  const addProperty = () => setProperties([
    ...properties,
    {
      id: 1 + Math.max(0, ...properties.map(n => n.id)),
    },
  ]);
  
  return (
    <> 
      <button onClick={addProperty}>Add</button>
      {properties.map(n => (
        <Property
          key={n.id}
          data={n}
          onDelete={() => delProperty(n)}
        />
      ))}
    </>
  );
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question