0

I have a component with functionally, let's say if you click on it, it does: alert("Hello World");

But now, let's say I want several components to have the same functionality, and these components can be expanded in the future, how can I do that in good way?

I thought about HOC but then I would have to decide which element to use, for example <div> but I want it to be generic so I could decide to put inside whatever element I need.

6
  • 1
    this is a perfect use case for creating your own hook Commented Apr 13, 2020 at 14:38
  • @azium what is the alternative if I use Class based components? Commented Apr 13, 2020 at 14:38
  • 1
    add the alert functionality to this.props.children Commented Apr 13, 2020 at 14:39
  • 1
    aka use render props reactjs.org/docs/render-props.html Commented Apr 13, 2020 at 14:41
  • 1
    @Dorki it is not an article, they are the official docs of react. Commented Apr 13, 2020 at 14:51

2 Answers 2

2

In many cases, I would suggest creating custom hooks or render props to reuse functionality. For your example, however, you could just have a very simple file:

// alert.js
const Alert = msg => ({
  onClick: () => alert(msg),
})

export default Alert

And use it like this:

const MyComponent = () => {
  return (
    <div { ...Alert('Hello World') }>
      click me
    </div>
  )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, could you add @azium link about how to do that in Class based component? this link: reactjs.org/docs/render-props.html so others could also see other options to implement that
1

Here is a potential solution I came up with that uses React's createClass function. You could rework to handle many (i.e. unlimited) elements within that main element, so that each child could have it's own tag, too

Comments

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.