Robert Gurjiev
Robert Gurjiev

Reputation: 520

How to create shared component in React correctly?

I have a class with a search form:

class LocalSearch extends React.Component {
  render() {
    return (
      <Container className="search-container pt-4">
        <InputGroup className="mb-3">
          <FormControl
            placeholder="Search events"
            aria-label="Search events"
            aria-describedby="basic-addon2"
          />
          <InputGroup.Append>
            <Button className="m-button">Find</Button>
          </InputGroup.Append>
        </InputGroup>
      </Container>
    );
  }
}

I will need this component in other pages too. So, I want to create a shared component for multiple uses with props. This is what I have done:

class SearchForm extends Component {
  render() {
    const {
      className, inputClassName, placeholder,
      ariaLabel, ariaDescribedby, buttonClassName,
      buttonName,
    } = this.props;
    return (
      <Container className={className}>
        <InputGroup className={inputClassName} />
        <FormControl
          placeholder={placeholder}
          aria-label={ariaLabel}
          aria-describedby={ariaDescribedby}
        />
        <InputGroup.Append>
          <Button className={buttonClassName}>{buttonName}</Button>
        </InputGroup.Append>
      </Container>
    );
  }
}

SearchForm.propTypes = {
  className: PropTypes.string.isRequired,
  inputClassName: PropTypes.string.isRequired,
  placeholder: PropTypes.string.isRequired,
  ariaLabel: PropTypes.string.isRequired,
  ariaDescribedby: PropTypes.string.isRequired,
  buttonClassName: PropTypes.string.isRequired,
  buttonName: PropTypes.string.isRequired,
};

I guess I'm doing something wrong. Just give me a hint on how I can improve my code. I also want: - to have props names as a default in shared component class (for not passing them every time) - to declare all props as string in propTypes and to match them as "no-required" due to default values

Upvotes: 0

Views: 109

Answers (1)

Vishnu
Vishnu

Reputation: 1701

You can initialize defaultProps for class components like:

class SearchForm extends Component {
  render() {
    const {
      className, inputClassName, placeholder,
      ariaLabel, ariaDescribedby, buttonClassName,
      buttonName,
    } = this.props;
    return (
      <Container className={className}>
        <InputGroup className={inputClassName} />
        <FormControl
          placeholder={placeholder}
          aria-label={ariaLabel}
          aria-describedby={ariaDescribedby}
        />
        <InputGroup.Append>
          <Button className={buttonClassName}>{buttonName}</Button>
        </InputGroup.Append>
      </Container>
    );
  }
}

SearchForm.defaultProps = {
  className: 'default-input',
  placeholder: 'Search',
};

Upvotes: 1

Related Questions