Soumalya Bhattacharya
Soumalya Bhattacharya

Reputation: 662

How to call a class component using onclick event handler in react.js

I have two files. File1 is a class component returning a class using export. File2 is a normal function component. I have a button in File2 I want to use onclick event handler to summon my file1 which I imported in file2. I'm including parts of my code.

import Comment from './commentForm';

<Button type="button" outline onClick= {***I want to call comment here***}>
  Send Feedback
</Button>

Comment is file1 and the button is on file2

Upvotes: 0

Views: 4868

Answers (3)

Mohan Teja Chitturi
Mohan Teja Chitturi

Reputation: 169

I assume, you want to call a class component method/s in the click handler of another component, lets say you have

  1. Class component : AClassComp in File1.jsx
  2. another component (functional or class) : ParentComp in File2.jsx

you can do the below

// File1.jsx

Class AClassComp extends React.Component{
   constructor(){ ...... }

   someMethod1=()=>{}
   someMethod2=()=>{}
   ...
   render(){.....}
}
export default AClassComp;
 //File2
 import 'AClassComp' from './File1.jsx'

 function ParentComp(){
   const classCompRef = useRef(null);

   const onClickButton= (e)=> {
     // you can access the Class comp methods here 
     // or do what ever you want using the AClassComp instance
     classCompRef.current.someMethod1();
   }

   return (
    <>
    <AClassComp ref={classCompRef}/>
    <Button onClick={onClickButton}
    </>
   )

 }

when you reference a class component it returns its instance .

Upvotes: 1

Paul Martin
Paul Martin

Reputation: 469

If you are importing a functional component from another file, you can simply add the variable in the onClick handler. It might be useful to see what 'Comment' actually does?

import Comment from './commentForm';

<Button type="button" outline onClick= {Comment()}>
  Send Feedback
</Button>

EDIT: Assuming Comment looks something like this...

const Comment = () -> {
   return comment
}

export default Comment

Upvotes: 0

Pierre Olivier Tran
Pierre Olivier Tran

Reputation: 1879

Your button should be integrated into a wrapping component, do something like this:

import React, { useState } from 'react'
import Comment from './commentForm';

const MyComponent = () => {
  const [displayed, setDisplayed] = useState()

  return (
    <div>
      { displayed && <Comment /> }
      <Button type="button" outline onClick={() => setDisplayed(true)}>
        Send Feedback
      </Button>
    </div>
  )
}

export default MyComponent

Upvotes: 1

Related Questions