Use Props !
Using props to highly customize your component is good practice, but too many props isn't always good ! You need to ask yourself:
- Am I trying to overly handle every situation possible ?
- Is it ok if a second component handles different cases ?
- Are these props absolutely required for my component to work as intended ?
If 1. and/or 2. is a yes and/or 3. is a no then you should probably rethink your component logic.
For your example, you're not overly using props.
Don't assume your props exist !
<input type={this.props.type} .../>
Get the props and set default values for them if they are undefined. Use destructuring for this:
render(){
const {
type = "text",
placeholder = "Type something",
id = null,
className = null
} = this.props;
return (
<input type={type} placeholder={placeholder} id={id} className={className} />
)
}
You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.
Using many props gets messy and it's easy to forget which props are being used and which props are required for your components.
Example:
export class Input extends React.Component{
/** code here */
}
Input.propTypes = {
id: PropTypes.number.isRequired, //required will throw error if id is not set
placeholder: PropTypes.string,
className: PropTypes.string, //optional
type: PropTypes.string, //optional
}
When to use classes and when not to use classes
Keep in mind that all your components don't need to be a class. Only use a class if the object becomes complex.
Keep things simple like so:
export const Input = props => {
const {
type = "text",
placeholder = "Type something",
id = null,
className = null
} = props;
return (
<input
type={type}
placeholder={placeholder}
id={id}
className={className} />
)
}