Search code examples
reactjsreduxreact-routerreact-reduxredux-router

React router open modal


I'm new to react and redux world. I have a question regarding react router. Following is my App component.

class App extends React.PureComponent {
  render() {
    return (
      <div>
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route exact path="/callback" component={CallbackPage} />
          <Route exact path="/list" component={List} />
          <Route component={NotFoundPage} />
        </Switch>
      </div>
    );
  }
}
export default App;

My list class looks like this:

export class List extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      isOpen: false,
    };

    this.depositHandleToggle = this.depositHandleToggle.bind(this);
  }
  depositHandleToggle = () => {
    this.props.dispatch(push(`${this.props.match.url}/deposit`));
  }
  render() {
    const { match } = this.props;
    return (
      <div>
      <Route path={`${match.url}/deposit`} component={Modal} />
        <button onClick={this.depositHandleToggle}>Open Modal</button>  
      </div>
    );
  }
}
export default List;

So my question is: when i click the button in List container, why my router can't find this url 'localhost:xxx/list/deposit'? it renders the App component but it never goes back to List component. Is it possible to have the custom routes inside my list container? Am i doing something wrong? Please someone help me with this.

I hope you understand my question. Thanks in advance.

ANSWER:

I found the answer, the issue was in my App component list route. I was having the 'exact' keyword, that's why route inside my list component was not working. Following way is the correct way.

<Route path="/list" component={List} />

I hope this will help someone.


Solution

  • import { Link } from 'react-router-dom';
    class App extends React.PureComponent {
      render() {
        return (
          <div>
            <Switch>
              <Route exact path="/" component={HomePage} />
              <Route exact path="/callback" component={CallbackPage} />
              <Route exact path="/list" component={List} />
              <Route exact path="/list/deposit" component={Modal} />
              <Route component={NotFoundPage} />
            </Switch>
          </div>
        );
      }
    }
    export default App;
    
    export class List extends React.PureComponent {
      constructor(props) {
        super(props);
      }
    
      render() {
        const { match } = this.props;
        return (
          <div>
          <Link to={'/deposit'}>Open Modal</Link> 
        );
      }
    }
    export default List;
    

    in that component you should handle modal open close.