I may be thinking about this wrong but I would like to have two components, a parent and a child, where the child has an input element where the user is expected to enter a number. The parent component's callback will only get called on valid numbers. This is enforced via Typescript and parseFloat.
class Child extends React.Component {
state = { number: '' };
inputChanged = (ev) => {
const stringy = ev.target.value;
this.setState({number: stringy});
const parsed = parseFloat(stringy);
if (parsed) {
this.props.numberChanged(parsed);
}
}
render() {
return <input
type="text"
value={this.props.number || this.state.number}
onChange={this.inputChanged}
/>
}
}
class Container extends React.Component {
state = { number: 5 };
numberSet = (value: number) => {
this.setState({number: value});
}
render() {
return <Child
number={this.state.number}
numberChanged={this.numberSet}
/>;
}
}
The challenge comes in that I want to be able to set and change the number value in the child component with props. But I also want to allow the user to type numbers in.
If I only rely on the props and not state then when they type things like decimal points they do not show up because they are invalid from the perspective of parseFloat. But if I only rely on state then I can't seem to get the parent component to update the child component with new props.
I have created the following CodePen to reproduce as well. Notice how you cannot type a decimal point in the input field. Where am I going wrong here?
This is enforced via Typescript and parseFloat- TypeScript has no bearing on your code once it is running....decimal points they do not show up because they are invalid from the perspective of parseFloat- what?