Reputation: 2150
I keep reading that when in doubt I should turn an element into a component. So are there actually any benefits to turning form elements such as <input />
to components.
Consider the following:
const SomeComp = (props) => {
return (
<form className='someClass' onSubmit={props.handleSubmit}>
<Input
className='someClass'
type='text'
id='someId'
placeholder='Enter Something'
onChange={props.handleChange}
value={props.side}
/>
</form>
)
}
Unless I'm using options like autoCorrect, autoCapitalize, spellCheck the only things I'll save by wrapping the input into a component like <TextInput/>
and importing it to various forms is not adding the type prop to each input and maybe the fact that the error for the input is not declared at the top of the form.
Is there anything else I'm missing? What's the most beneficial way to approch such form elements and why?
Upvotes: 1
Views: 3743
Reputation: 19967
I use styled-components
and do stuff like this all the time. The basic idea with Styled Components is that you attached CSS
styles to your component instead of creating CSS
classes to target, for example, all input
elements or using inline styles
which limit what you can do (i.e. media queries, psuedo-selectors, etc). And it allows you to separate your components functionality from it's presentation (within the same file).
Here is a link to a youtube video on the topic: https://www.youtube.com/watch?v=jaqDA7Btm3c
This way, you avoid the need for a global CSS
file that is hard to maintain and doesn't exactly fit well within the webpack
ecosystem that views your assets as a graph of dependencies.
If you are not interested in styled-components
, and are happy with the way you style your form elements, then I see no reason to create a custom Input
component.
For example, in Facebook's docs on React forms, they do not create custom form components.
https://facebook.github.io/react/docs/forms.html
Unrelated:
If you don't already know, you can write your example like so:
const SomeComp = props =>
<form className='someClass' onSubmit={props.handleSubmit}>
<Input
className='someClass'
type='text'
id='someId'
placeholder='Enter Something'
onChange={props.handleChange}
value={props.side}
/>
</form>
(removed the ()
around the single argument, and removed the {}
and return
statement. Like I said, unrelated, but thought I would mention it in case you were not aware.
Upvotes: 1
Reputation: 33
Usually you will not want to turn very simple elements like inputs into separate components, unless you are expecting some special functionality from them.
The simplest way to go through is to always have, for each functional need (like a login page for example), a smart component for handling the behavior and functionality, and one dumb components for displaying the ui elements.
When you start feeling there is too much code in some of your smart components, or a dumb component has gone to large you can start dividing them. Otherwise try to keep it simple.
Upvotes: 2