Search code examples
reactjssemantic-uisemantic-ui-react

Dynamically set a property value for an Input in Semantic UI React


I have an Input element that I want to display an error on when the form validation fails.

<Input ref="amount" error={false} />

When the user enters an incorrect amount, I want to change "error" to "true". How can this be done?

I have tried:

this.refs.amount.props.error = true;

Which seems bad but I'm not sure how else. If I add a conditional statement in the definition of the Input element, that seems to only evaluate once and then remain the same. Do I need to force an update on the element? If so, how?


Solution

  • Use the onChange() method on the input as below.

    <Input ref="amount" onChange={this.onInputChange} error={this.state.error} />
    

    After that implement the onInputChange() method as below in your component.

    onInputChange = (e) => {
        if (e.target.value === "") { // logic to validate the input
            this.setState({error: true});
        } else {
            this.setState({error: false});
        }
    }
    

    Note that this will add error property to the state.

    Further, you should not modify the props within a component. Props are passes from parent component to the child component as immutable inputs.