Home > front end >  How to reuse a component if it should be slightly different?
How to reuse a component if it should be slightly different?

Time:09-30

Is it possible to somehow make a slider component in react and reuse it if it is slightly different? The second one has a 13% field

enter image description here

CodePudding user response:

You can create that component as a reusable one-based requirement. You can manage that component based on the passing props. Regarding props, you can learn here

Let's take one example and understand it.

Example:

import React from 'react';
import PropTypes from 'prop-types';

const Button = (props) => {
  const { title, type, onClick, isDisabled, ...rest } = props;

  return (
    <button
      {...rest}
      type={type}
      onClick={onClick}
      isDisabled={isDisabled}
    >
      {title}
    </button>
  );
};

Button.propTypes = {
  title: PropTypes.string,
  type: PropTypes.string,
  isDisabled: PropTypes.bool,
  onClick: PropTypes.func,
};

Button.defaultProps = {
  title: 'Save Changes',
  type: 'button',
  isDisabled: false,
  onClick: () => { },
};

export default Button;

So we have one button component and will be using based on a different scenario via passing the props.

<Button
 title="Save"
 isDisabled={true}
/>

<Button
 title="Reset"
/>

<Button
 onClick ={() => { //do something }}
 title="Submit"
/>

<Button
 title="Continue"
/>

In this way, you can create your component and reuse it.

  • Related