0

I have many working components im my React application. I want add the functionality of displaying a simple error/warning message (for the sake of the simplicity, just a H1 elem on the top) when the component (that can be a whole window/form) find some problem.

For example, in a form that change a password, It would be nice to have something like:

onSubmit(event) {
...
if (!this.state.password1 === this.state.password2) {
   this.showError("The passwords don´t match"}
...
}

My first intent is was using inheritance, defining a super class this way:

export default class MostrarError extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: '' };
  }

  mostrarError(msg) {
    this.setState({ error: msg });
  }

  render() {
    return (
      <React.Fragment>
        {this.state.error ? <h1> UPS! {this.state.error} </h1> : null}
        this.props.children
      </React.Fragment>
    );
  }
}

but, the super render() method will be never be called, because each subclass defines its own render(). I can use some kind of Method Template, but it involves modifying all subclasses.

This is surelly a very common problem, but most solutions I found makes use of Redux, and I cant use it.

Can someone point me to some other solution?

1 Answer 1

1

I think what you're looking for is to have one single alert component that can communicate with parent component and conditionally render itself.

Why not do something like this in your parent component

export default class ParentCompo extends React.Component{
   state = {
     error: false,
     errorMsg: ''
   }
   onSubmit = () => {
    if(this.state.password1 !== this.state.password2) {
       this.setState({error: true, errorMsg: 'Passwords dont match'})
    }   
   }
   render(){
      return (
         <div>
            <AlertCompo error={this.state.error} errorMsg={this.state.errorMsg} />
            Normal stuff here...
         </div>
      )
   }
}

Your alert component should look something like this

export default class AlertCompo extends React.PureComponent{
    shouldComponentUpdate(nextProps){
        if(nextProps.error !== this.props.error){
            return true;
        }
        return false;
    }
    render(){
        if(this.props.error){
           return (
              <h1>Some alert message {this.props.errorMsg}</h1>
           )
        }else {
           return <React.Fragment />
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.