How to conditionally render error and success messages on the click button?

Am trying to pop some messages (error and success messages) when i submit the form onClick button, when the user has not given a feedback and tries to submit, i pop up an error message. When the user field at least one field in the form and submits, a success messages pops up but i want to call back the cancel button after successful submission with the success message.
I have achieved it but am failing to call back the cancel button with the success message when the form has successfully submitted.

Any one with a suggestion on my code how i can achieve it?.

Here is my code

import React, { Component } from 'react';
import FormControl from '@material-ui/core/FormControl';
//import InputLabel from '@material-ui/core/InputLabel';
//import Input from '@material-ui/core/Input';
//import FormHelperText from '@material-ui/core/FormHelperText';
import TextField from '@material-ui/core/TextField';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
//import green from '@material-ui/core/colors/green';
//import Radio from '@material-ui/core/Radio';
//import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked';
//import RadioButtonCheckedIcon from '@material-ui/icons/RadioButtonChecked';
import Rating from 'material-ui-rating';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    fullWidth: true
  },
  container: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  textField: {
  },
  menu: {
    width: 200,
  },
  submit: {
    width: "100px",
    margin: "7px"
  },
  submitContainer: {
    textAlign: "right",
  },
  table: {
    width: "100%",
    paddingTop: 20
  },
  tableText: {
    textAlign: "left",
    fontSize: 20
  }
};

class Feedback extends Component {
  constructor(props) {
    super(props);
    this.state = {
      customer_service: 0,
      staff_knowledge: 0,
      free_text: '',
    };

    this.handleRatingSelect = this.handleRatingSelect.bind(this);
    this.handleFreeText = this.handleFreeText.bind(this);
  }

  handleRatingSelect(rating, value){
    console.log(`${rating}:  ${value}`);
    this.setState({[rating]: value});
  }

  handleFreeText(event) {
    this.setState({
      free_text: event.target.value,
    })
  }

  postComment = (e) => {
    if(e) e.preventDefault()
    let x = this.state.customer_service;
    let y = this.state.staff_knowledge;
    let z = this.state.free_text;
    let error = document.getElementById('errorMessage');
    let success = document.getElementById('notification');

    if (x === 0 && y === 0 && z === '') {
      error.innerHTML = '<i class="material-icons"">error_outline</i> You can not submit a blank feedback!';
      error.style.color = 'red';
      error.style.textAlign = 'right';
      error.style.fontSize = '20px';
    } else {
      success.innerHTML = '<i class="material-icons" id="material-ui">check_circle</i> Feedback submitted successfully!!!..Thanks!';
      success.style.color = '#4CAF50';
      success.style.backgroundColor = '#ddffdd';
      success.style.borderLeft= '6px solid #4CAF50';
      success.style.opacity= 1;
      success.style.transition= '0.1s';
      success.style.padding = '20px';
      success.style.width = '50%';
      success.style.margin = 'auto';
      success.style.fontSize = '20px';
      success.style.transition= 'width 2s, height 2s, -webkit-transform 2s';
      document.getElementById("material-ui").style.color = "#4CAF50";
      document.getElementById("hide-form").style.display = "none";
      console.log('data submitted successfully !');
    }    
  }
  

  render() {
    const { classes } = this.props;

    console.log(classes);

    return (
      <div>
        <div id='notification'/>
        <FormControl fullWidth="true" id="hide-form">
        <h2 id="">Please rate your recent visit with us!!</h2>
        <table className={classes.table}>
          <tr>
            <td id='errorMessage' />
            <td></td>
          </tr>
          <tr>
            <td className={classes.tableText}>Rate your customer service experience during your visit.</td>
            <td>
            <Rating
              value={this.state.customer_service}
              max={5}
              onChange={(value) => this.handleRatingSelect("customer_service", value)}
            />
            </td>
          </tr>
          <tr>
            <td className={classes.tableText}>How knowledgeable was the staff who served you.</td>
            <td>
            <Rating
              value={this.state.staff_knowledge}
              max={5}
              onChange={(value) => this.handleRatingSelect("staff_knowledge", value)}
            />
            </td>
          </tr>
        </table>
        {/*
        <TextField id="standard-full-width"
            label="Name" style={{ margin: 8 }}
            placeholder="" helperText="Optional"
            fullWidth margin="normal"
            InputLabelProps={{
              shrink: true,
            }}
          />

        <TextField id="standard-full-width"
            label="Phone Number" style={{ margin: 8 }}
            placeholder="" helperText="Optional"
            fullWidth margin="normal"
            InputLabelProps={{
              shrink: true,
            }}
          />

        <TextField id="standard-full-width"
            label="Email" style={{ margin: 8 }}
            placeholder="" helperText="Optional"
            fullWidth margin="normal"
            InputLabelProps={{
              shrink: true,
            }}
          />
        */}
        <td className={classes.tableText} style={{marginTop: 20}}>
          What can we do to improve our services ?
        </td>
      
        <TextField
          id="outlined-textarea"
          value={this.state.free_text}
          onChange={this.handleFreeText}
          label=""
          required
          placeholder=""
          multiline
          rows="4"
          margin="normal"
          variant="outlined"
        /> 
        
        <div className={classes.submitContainer}>
          <Button variant="contained" className={classes.submit} 
            size="medium" onClick={() => this.props.onCancel()}>
            Cancel
          </Button>
          <Button variant="contained" color="primary" className={classes.submit} 
            size="medium" onClick={() => this.postComment()}>
            Submit
          </Button>
        </div>
      </FormControl>
      </div>
      );  
    };
};

Feedback.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(Feedback);

Why would you want to do that, and what would it achieve?

Hi Paul;
In fact, I have hidden the form after successful submission but i want to display the cancel button so that the users can click on it and are redirected back to the homepage.

Then you are attempting to use the Cancel button for the wrong purpose.

What needs to be done instead is to show a button or a link that says something like “Return back to the home page”, optionally also with a message saying that they will be redirected back to the home page within 10 seconds.

1 Like

Okay Paul let me give it a trial. Thanks

I have added a link here but still it can’t take me back to the home page

 <Link to="/" className="go-forward">
     <i className="material-icons">
       fast_forward
     </i>  
     Home  
  </Link>

Here is my route

<div>
   <Route path="/" exact render={() => IndexPage(this.props)}/>
 </div>

That doesn’t look to be JavaScript, and I can’t help when it comes to React. Somebody that knows something about that will have to assist from here instead.

Oh yeah !. am using react.

It’s alright Paul. Hope someone else can help.

Thanks Paul for your positive replies.

Hi @namwanzaronald4, can’t you just call this.props.onCancel() at the bottom of the postComment() method then (or if you’re actually submitting the form with AJAX, inside the respective success callback)?

Other than that it’s hard to tell without knowing what that onCancel() callback looks like… it’s not even in your prop types BTW. A router link would be an option too, but it’s again hard to tell why it doesn’t work without a bit more context… can you put together a minimal example on stackblitz or code sandbox or something that demonstrates the problem?

Hi @mentor, linking it using the old way like this <a href="/">Click to go back</a> works though i think that would not be a better way to link a component as i prefer using React Router as a better solution to this like
<Link to="/">Click to go back</Link> but i really don’t know why it’s failing to work. However, I have decided to use a button as @Paul suggested in the first place

<Button className={classes.linkButton}  onClick={() => this.props.onCancel()}>
    <i className="fa fa-home"/>
</Button>

though on the home icon and everything seems to be working fine. Thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.