I'm relative new to react and I need to create a character counter component (CharacterCounter) for a input field.
This question is not specific to this component (character counter) - but is a generic question about components best practices in general.
I can implement in two ways (as far I know - if there are better ways I'm happy to hear about it):
1) Wrapping the component and have the input field as a child - The component will insert the span (for showing the counter) after the input field
<CharacterCounter maxLength={50}>
<input type="text">
</CharacterCounter>
and
const input = this.container.firstChild
input.addEventListener('keyup', function() { ... });
- advantage: I can have multiple components for the same input - if I need extra functionality (components) for this input.
- disadvantage: If the input for some reason stop being the first child of this component - stop working/ fragile
2) To create a generic component which will render the input and the counter on the render() function
like:
<CharacterCounter />
render() {
return (
<input type="text">
<span>{this.state.count}</span>
)
- advantage: Not fragile - not relying on the first child
- disadvantage: Not sure is possible to have other component for the same input - let's say I need another component for tracking every time the user type/ or focus/ or blur the field
What is the best practices?
