1

I have component with a trigger Element, the trigger Element is A react component like the following

const TriggerComponent = () => <div> trigger example </div>

<MyComponent  trigger={<TriggerComponent />} />

Inside the MyComponent class, I want to add a ref attribute to the trigger Element by cloneElement or creatElement API, of course, I can't add a ref attribute to a functional component according to react documentation. So my idea is to convert the function component to class?

lets me know if you have any idea on how can I implement this idea?

1
  • you want to get a ref from the TriggerComponent ? Commented Feb 17, 2018 at 15:07

2 Answers 2

1

The best way to add ref to stateful component children is by creating a class Ref and inject your function component as a child like the following :

class Ref extends React.Component {
constructor(props) {
  super(props);
}
componentDidMount() {
  const { innerRef } = this.props;
  if (innerRef) innerRef(findDOMNode(this));
}
render() {
  const { children } = this.props;
  return React.Children.only(children);
}

}

and we can add ref to function component.

const Trigger = ()=> <button> trigger </button>
const RefTrigger = () => <Ref innerRef={this.setRef}><Trigger/></Ref>
Sign up to request clarification or add additional context in comments.

Comments

0

You can pass a ref callback to a stateless component:

const TriggerComponent = ({ triggerRef }) => <div ref={triggerRef}> trigger example </div>

Running example:

const TriggerComponent = ({ triggerRef }) => <div ref={triggerRef}> trigger example, click me </div>

class App extends React.Component {
  componentDidMount(){
    this.trigger.addEventListener('click', () => { console.log('triggered') });
  }

  render() {
    return (
      <div >
        <TriggerComponent triggerRef={ref => { this.trigger = ref }} />
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

1 Comment

Hi Sagiv, the component is built for a simple lib, so I think it's more useful if I don't add extra condition to the trigger prop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.