The buttons will have for example 3 sizes: small, medium, large and for example 3 colors

How best to implement such a component and to be comfortable to use?

  • Output this data to the props (inside the component itself) and when connecting it from the outside specify the one you need. - Kvilios
  • For such cases, there are "defaults": reactjs.org/docs/… - Kvilios

2 answers 2

Option number 1 (simple condition):

import React from "react"; export default class Button extends React.Component { render() { const { size, variant, text, children } = this.props; return ( <div className={`btn-size-${size || "medium"} btn-variant-${variant || "default"}`} > <span className="btn-text">{text || children}</span> </div> ); } } 

Option number 2 ( PropTypes ):

 import React from "react"; import PropTypes from "prop-types"; class Button extends React.Component { render() { const { size, variant, text, children } = this.props; return ( <div className={`btn-size-${size} btn-variant-${variant}`} > <span className="btn-text">{text || children}</span> </div> ); } } Button.defaultProps = { size: "medium", variant: "default", }; Button.propTypes = { size: PropTypes.oneOf(["small", "medium", "large"]), variant: PropTypes.oneOf(["primary", "secondary", "disabled", "default"]), text: PropTypes.string }; export default Button; 
  • You can replace the text with props.children so that you can render <Button ...>Все что угодно</Button> - Dmitry Kozlov
  • @DmitryKozlov agree - Alexandr Tovmach
  • Option number 2. How, then, to use button large? we have a default medium. Just when to render in props to write? - stiv
  • Well, yes, what do you want?) - Alexandr Tovmach pm
  • something like this and represented) the text is also in the props to write? - stiv

You can also create ready-made buttons with classes, styles, etc., and then just call them:

buttons

 export const DarkButton = props => <button type="button" className="btn btn-outline-dark" {...props}/>; export const DangerButton = props => <button type="button" className="btn btn-outline-danger" {...props}/>; 

call:

 render(<div> <DarkButton>dark button</DarkButton> <DangerButton>danger button</DangerButton> </div>) 

button properties can be overridden:

 <DarkButton className="...">dark button</DarkButton> 
  • yeah well ... with options of three colors and three sizes it turns out 9 buttons, why? - Alexandr Tovmach