Building reusable form components in React🚀
Building reusable components, It's super easy and powerfulâš¡
You save a lot of development time by building reusable components. Let's see how you can build reusable form components such as input and button in react. It's super easy, So let's get started🚀
Input component
Step 1: Create components folder inside src
Step 2: Create Input folder inside components
Step 3: Create Input.js inside Input
Inside the Input.js, create a function Input which will accept props as argument and will return input element
const Input = (props) => {
const { className, onChange, ...rest } = props;
const rootClassName = cn(styles.root, {}, className);
return(
<input
className={rootClassName}
onChange={handleOnChange}
{...rest}
/>
)
export default Input;
Here, className and onChange is destructured from the props and other arguments passed is destructured into rest variable. The classNames passed in the arguments and the root className is combined using classnames package availabe in npm.
You can install it using:
npm i classnames
onChange function is handled using the function:
const handleOnChange = (e) => {
if (onChange) {
onChange(e.target.value);
}
return null;
};
Input component will accept all the attributes which is supported by the input element and is passed to the input element using spread operator {...rest}
Usage of the component:
<Input
placeholder="Enter your name"
value={name}
onChange={setName}
style={{ width: "30%" }}
/>
Button component
Step 1: Create Button folder inside components
Step 2: Create Button.js inside Button
Inside the Button.js, create a function Button which will accept props as argument and will return button element
const Button = (props) => {
const { children, loading = false, disabled = false, ...rest } = props;
const rootClassName = cn(styles.root, { [styles.disabled]: disabled });
return (
<button disabled={disabled} className={rootClassName} {...rest}>
{loading ? "loading" : children}
</button>
);
};
export default Button;
Here, while the usage of the component user can pass loading, disabled and other button attributes and they all are destructured and applied to the component. loading and disabled will be defaultly set to false so that even if the user doesn't pass those arguments, component will work fine. The children prop will be anything inside the component passed.
Usage of the component:
<Button
style={{ width: "30%"}}
onClick={handleLogIn}
>
Log in
</Button>
Pro Tip💡
Export your component inside index.js so that the usage is easy
export { default } from "./Button";
Your directory will look like:
That's it folks! Thank You for reading.