I'm trying to create a component that serves to validate routes, the purpose is to pass through a property called protect
, the component I want to validate and other properties where I want to redirect if it fails.
The problem is when I try to use this component two or more times, it only works for the first one, looking for I realized that the properties for the components instantiated after the first one are not taking them there is some way to binde these properties for each component in which they are used?
class PrivateTwo extends React.Component {
constructor(props) {
super(props);
this.Component = this.props.protect;
this.customPath = this.props.customPath;
this.toFailed = this.props.toFailed;
this.validate = this.props.validate;
}
render() {
let Component = this.Component;
console.log(this.customPath);
return (
<Route
path={this.customPath}
render={props => {
if (this.validate) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{
pathname: this.toFailed,
state: { from: this.props.location }
}}
/>
);
}
}}
/>
);
}
}
export default PrivateTwo;
the way it is used:
<Switch>
<Route exact path="/" component={Home} />
<PrivateTwo
customPath="/inner"
protect={Inner}
validate={this.props.current} // si es true puedo acceder a la ruta
toFailed="/" // ruta a donde redirijo si falla la validacion
/>
<PrivateTwo
customPath="/contact"
protect={Contact}
validate={this.props.current} // si es true puedo acceder a la ruta
toFailed="/"
/>