Reputation: 2807
This is a simplified code. Here is a button component:
import React from 'react'
import styles from './Button.module.scss'
const Button = (props) => {
return (
<button type={props.type} className={styles.btn} onClick={props.handleClick}>{props.text}</button>
)
}
export default Button
I'd like to reuse this component in multiple places. My issue is that i have a form where i don't need to provide any handleClick
logic. So i just simply omit it:
<form onSubmit={handleFormSubmit} >
*form related code*
<Button text="Submit" type="submit" />
<form/>
And in places where i need some handleClick
logic i pass it:
<Button text="Do Something" type="button" handleClick={()=> console.log('clicked')} />
Is it a correct way to reuse a component or should i have 2 different components in this case? It does not feel ok to make it reusable by not passing props. Thank you.
Upvotes: 0
Views: 267
Reputation: 289
Sometimes it is difficult to decide. So I always go with intent. Every component has an intent/purpose. If we use a property to customize the behavior slightly, then it is completely fine. Button
with an optional handle for click binding.
But when we do with some important properties which could make the component behave like a different component (different intent), then it is better to go with two components to avoid ambiguity in usage. like ClickableButton
and SimpleButton
.
Upvotes: 0
Reputation: 2938
It's perfect, in the matter of fact, making a component re-usable via it's props is the best practice, and unless this way makes a component unnecessarily complicated then don't use it, and go for the Two Components approach instead.
Tip: we have a component A
, it's already re-usable, but, we want to add another feature to it, to support an other use case, but it'll make the component complicated, in this case, building a new component A2
is preferable.
Upvotes: 1
Reputation: 272
I believe that it is completely fine to not pass props to components. In a large number of libraries, there are default props. In the PropTypes library, you can use defaultProps
to provide default values so the developer does not have to specify them every time.
Upvotes: 1