title: Removing elements from array by clicking on them in React
body: <p>I have an array of messages, that are rendered into react components with array.map and key=index (in array). The array is saved to a state. I would like the messages to close, when I click on the button in the message component. I thought about passing the key variable to the Messages Component so I could use it in the closeMessage function by calling target.key somehow, but when I call the the key attribute I only get undefined. Any idea how I can do this? Thanks in advance!</p>
  <pre><code>function Register () {
  
  const [errors, setErrors] = useState([{ msg: 'abc' }, { msg: 'cde' }]);
  
  const closeMessage = ({target}) =&gt; {
          setErrors(errors =&gt; errors.splice(target.key, 1));
      }
  
  return (
  &lt;div className=&quot;register-container&quot;&gt;
      &lt;h1&gt;Register&lt;/h1&gt;
      {errors.map((error, index) =&gt; &lt;Messages alert=&quot;warning&quot; msg={error.msg} key={index} close={closeMessage}/&gt;)}
  &lt;/div&gt;
  )
  };
  </code></pre>
  <pre><code>function Messages (props) {
  
      return(
          &lt;div className={'message '+props.alert} key={props.key} onClick={props.close}&gt;
              {props.msg}
              &lt;button type=&quot;button&quot; className=&quot;message-close&quot;&gt;
                  &lt;span&gt;&amp;times;&lt;/span&gt;
              &lt;/button&gt;
          &lt;/div&gt;
      )
  }
  </code></pre>