can we able to specify on click on the component definition itself?

Viewed 32

I want to create a component(comp) with onclick event handler. which should be handled by the component itself (i.e. inside the comp.js file). if I use it inside the parent component we don't need to specify the event but it is handled by the component element(comp element).

is this possible. Any idea to develop this one.

in ParentComponent.js current behavior.

<NewComponent onClick={clickBehaviour}/>

I want like, In NewComponent.js

const NewComponent.js = ()=>{
    // Some code
    const clickBehaviour = () =>{
        // click behaviour
    }
}

Is it possible in the current standards?

1 Answers

why you want to write your onClick event in parent component? you can do it inside NewComponent.js easily. just do this:

import React from 'react'

function NewComponent() {

    const clickBehaviour = () =>{
        // click behaviour
    }

    return (
        <div onClick={clickBehaviour}>
            //some jsx here
        </div>
    )
}

export default NewComponent

and use in anywhere you want to use without onClick event :

< NewComponent />

i cant understand well you situation but you can use forwardRef if you want (also can use old getElementById but using forwardRef is recommended).

import React, { useRef } from "react";

const NewComponent = React.forwardRef((props, ref) => (
  <div onClick={() => alert("div 2 clicked")} ref={ref}>
    div 2
  </div>
));
export default function App() {
  const compRef = useRef(null);
  return (
    <div>
      <NewComponent ref={compRef} onClick={() => {
          compRef && compRef.current && compRef.current.click();
        }} />
    </div>
  );
}
Related