0

This is the input for image url

 <input className="imageInput" placeholder="upload url" onChange={this.onInputChange}/>

onChange change the state of input to the target value

onInputChange = (event)=> {
    this.setState({input:event.target.value});
}

and there is an update button that update imageUrl as input

<div class="update_button"onClick={this.onUpdate}>Update</div>

onUpdate = () => {
    this.setState({imageUrl:''})
}

Now while clicking the update button will change the input section with image. I use ternary operator

{this.state.imageUrl ? <!--show image here --> :<!-- shows input--> }

What i need to create is an error message if there is no image while clicking update button. The problem is while the state.imageUrl is empty, it show input section instead of error message. So how to know the presence of image and display the error message ?

1
  • Don't you want to do this.setState(state => ({ imageUrl: state.input })); inside onUpdate instead?
    – Tholle
    Commented Dec 23, 2020 at 4:13

2 Answers 2

0

Maybe you want your error message displayed on a condition:

{this.state.imageUrl === "" ? <p>Error, no image uploaded<p/> : null}

Put this statement anywhere you want to place the error message, customize it however you want.

1
  • Hi Viet, it is not working. because this.state.imageUrl === " " will display the input field. we have already set the empty imageUrl to display input.
    – Tony
    Commented Dec 23, 2020 at 7:00
0

You can create a isError variable in your state and in onUpdate function check if the imageUrl is empty and set the isError to true

onUpdate = () => {
    if(!this.state.imageUrl){
        return this.setState({isError: true})
    }
     this.setState({imageUrl:''}); // if success
}

in the ternary operator check if isError first and make a button to set it back to false to show the input again.

  {this.state.isError ? 
  <p>Error message <button onClick={()=>this.setState({isError: false})}>Try Again</button> </p> : 
  this.state.imageUrl ? 
  <!--show image here --> :
   <!-- shows input--> }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.