You can use spread operator to reduce code.
class TextInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return <input {...this.props} />;
}
}
export default TextInput;
This way you even don't need a seperate PasswordInput component.
<TextInput id="name" type="text" placeholder="Your Name" />
<TextInput id="password" type="password" />
Answer from SuleymanSah on Stack OverflowWhat is the proper way to create reusable components react
Is it always a good practice to do reusable components ?
Is it not possible to create reusable components like React in templating languages
Best practices for reusable forms
Videos
You can use spread operator to reduce code.
class TextInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return <input {...this.props} />;
}
}
export default TextInput;
This way you even don't need a seperate PasswordInput component.
<TextInput id="name" type="text" placeholder="Your Name" />
<TextInput id="password" type="password" />
Let's say your reusable component is named FormInput
The component definition should look like this:
const FormInput = (props: any) => {
const [value, setValue] = useState(props.value);
useEffect(() => {
setValue(props.value);
}, [props.value])
return (
<input
autoComplete={props.autoComplete}
name={props.name}
type={props.type}
id={props.id}
value={props.value}
data-index={props.index}
onChange={props.onChange}
disabled={props.disabled}
ariaLabelledBy={props.ariaLabelledBy}
required={props.required}/>
)
};
And in the page where you want to use it you can simply invoke the component pass all the props to the component and implement the onChange event handler on the page:
Let's say you want to invoke the Input component on Login page:
const LoginPage = (props: any) => {
... // you have some useEffect etc. that is related to the business logic of the page
const handleChange = (event: any) => {
// put your logic here
}
return (
... // other HTML elements/components
<FormInput type="text" onChange={handleChange} id="test" value="John Doe" ... />
)
};
Hello all, i'm a junior dev working on a React app and i'm in the process of coding a simple data table with pagination and such .. Usually i'm trying to set up reusable components for buttons and inputs as it is simple to do but for the data table it's taking the complexity of the component to a new level if i try to make it reusable.
So the question is : Is it always a good idea to make components reusable even if they're used like 6 times at most in the whole app and it makes the code more complex ?