Search code examples
reactjseventsclone

Add events to cloned component


I'm using the following method to clone a component and modify its props.

    const clone = React.cloneElement(<BallComponent>, {
        key: new Date().getTime()
    });

How can I add a click event to this cloned component and call a function within its class when clicked? I have tried the following with no luck:

    const clone = React.cloneElement(<BallComponent>, {
        key: new Date().getTime()}
        onClick: alert('test');
    });

Solution

  • You're closing the props object curly brace before. Also, pass onClick a function rather than calling alert there which will execute right when the component mounts.

    const clone = React.cloneElement(<BallComponent>, {
        key: new Date().getTime()
        onClick: () => { alert('test') }
    });
    

    This is a minimal example for the usage of React.cloneElement.

    import React from "react";
    import ReactDOM from "react-dom";
    
    class Demo extends React.Component {
      render() {
        return <p onClick={this.props.click}>This is Demo. Click me.</p>;
      }
    }
    
    function App() {
      const clone = React.cloneElement(<Demo />, {
        click: () => {
          alert("You clicked Demo :)");
        }
      });
    
      return (
        <div className="App">
          {clone}
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);