'How to trigger re-render in Parent Component from Child Component

, Using props I was able to effectively pass state upwards from my child component to its parent, but a change in the state does not cause a re-render of the page.

import React, { useState } from "react";

export default function App() {
  const AddToList = (item) => {
    setText([...text, item]);
  };
 const removeFromList = (item) => {
    const index = text.indexOf(item);
    setText(text.splice(index, 1));
  };
  const [text, setText] = React.useState(["default", "default1", "default2"]);
  return (
    <div className="App">
      <div>
        <button
          onClick={() => {
            AddToList("hello");
          }}
        >
          Add
        </button>
      </div>
      {text.map((item) => {
        return <ChildComponent text={item} removeText={removeFromList} />;
      })}
    </div>
  );
}

const ChildComponent = ({ text, removeText }) => {
  return (
    <div>
      <p>{text}</p>
      <button
        onClick={() => {
          removeText(text);
        }}
      >
        Remove
      </button>
    </div>
  );
};

In the snippet, each time AddToList is called, a new child component is created and the page is re-rendered reflecting that. However, when i call removeFromList on the child component, nothing happens. The page stays the same, even though I thought this would reduce the number of childComponents present on the page. This is the problem I'm facing.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source