Problems in validating routes in react

1

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="/"
   />

    
asked by Carlos Puente 28.10.2018 в 04:35
source

1 answer

0

The problem is that the constructor is called only when the component is created, you could use some method of one component life cycle , as componentDidUpdate() , validate that the props are different and assign the values to your variables.

Or you could use the values of the props directly in the function render()

class PrivateTwo extends React.Component {
  render() {
    const {
      protect,
      customPath,
      toFailed,
      validate,
      location 
    } = this.props;
    const MyComponent = protect;

    console.log(MyComponent);
    return (
      <Route
        path={customPath}
        render={props => {
          if (validate) {
            return <MyComponent {...props} />;
          } else {
            return (
              <Redirect
                to={{
                  pathname: toFailed,
                  state: { from: location }
                }}
              />
            );
          }
        }}
      />
    );
  }
}
    
answered by 28.10.2018 / 05:46
source