Uzair Khan
Uzair Khan

Reputation: 2970

Getting event from imported component in React

Hi I have my button component as shown:

ButtonComp.js------
class ButtonComp extends Component {
   render() {
     <button onChange={this.props.onChangeHandler} /> // I can pass event from button to datamaker
   }
}

My datamaker.js as follows:

dataMaker.js---------
import ButtonComp from '....';

 function onChangeHandler() {
}

function getSomeJsx() {
   return(
      <p>Hello</p>
      <ButtonComp onChangeHandler={onChangeHandler()}/> 
   );
}

const dataMaker = [
  {style: {..}, val: getSomeJsx()},
  {style: {..}, val: getSomeJsx()},
];
export default dataMaker;

And my main component:

MyComp.js-------
import datamaker from '../datamaker'

class MyComp extends Component {

   onChangeTriggerHere = () => {
      // I need the event here
   }

   render() {
     <div>
        datamaker.map(node => (
          <div style={node.style}>
             {node.val} ///which will render ButtonComp here
          </div>
        ))
     </div>
   }
}

Since value in MyComp, node.val is coming as data, which in turn is rendering ButtonComp, I really have no way in my MyComp to know if the event has actually happened. Is there any way with this structure, that MyComp can get the event arising from ButtonComp?

Upvotes: 0

Views: 154

Answers (2)

Manish Sundriyal
Manish Sundriyal

Reputation: 631

So you want the function onChangeTriggerHere in MyComp.js to be called when onChange is called inside ButtonComp.js.

So you need to pass down your function (onChangeTriggerHere) till ButtonComp.js component.

MyComp (onChangeTriggerHere) -> dataMaker -> ButtonComp

So there are 2 cases:

Case 1: You want both dataMaker & MyComp to act when the onChange event happens. If this is the case then just pass-down the onChangeTriggerHere as a prop to dataMaker and then use it inside onChangeHandler of dataMaker. Similarly, then pass-down the onChangeHandler as a prop to ButtonComp.

Case 2: You just want your MyComp to act when the onChange event happens. If this is the case then use Context API of React, to avoid prop drilling.

Upvotes: 0

MohammadAmin Mohammadi
MohammadAmin Mohammadi

Reputation: 1211

You can modify dataMaker as follow:

function getSomeJsx(callback) {
  return (
    <div>
      <p>Hello</p>
      <ButtonComp onChangeHandler={callback}/> 
    </div>
  );
}

const dataMaker = [
  {style: {..}, val: callback => getSomeJsx(callback)},
  {style: {..}, val: callback => getSomeJsx(callback)},
];

And in your myComp:

class MyComp extends Component {
  onChangeTriggerHere = () => {
    // I need the event here
    alert('ok');
  };

  render() {
    return datamaker.map(node => (
      <div style={node.style}>{node.val(this.onChangeTriggerHere)}</div>
    ));
  }
}

Upvotes: 1

Related Questions