Exporting methods in react component

2k Views Asked by At

Requirement is to create component whose methods can be accessible to other component so that from through other component we can give alert massage. ( Like toaster)

I know we can do this by following methods:

  1. statics - React.createClass or static in es6 class.

  2. Using ref of component.

But what is the best way to achieve this?

1

There are 1 best solutions below

3
On

That would look very funky and wouldn't follow the data-down actions-up React approach.

You could use a render prop instead:

// App.jsx
<AlertProvider>
  {sendAlert => <Consumer onAlert={sendAlert} />}
</AlertProvider>


// AlertProvider.jsx
export default class AlertProvider extends React.Component {
  sendAlert(msg) { alert(msg); }
  render() {
    return this.props.children(this.sendAlert);
  }
}


// Consumer.jsx
export default function Consumer({ onAlert }) {
  return <button onClick={() => onAlert('Boom!')} />
}

If you need it to be globally available, consider to use something like Redux.