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?