-1

I've been trying to work my way around this matter for a long time now and it seems I can't find a solution.

For a couple of circumstances the project I'm working with can't use React-Router on Rails, but I heard there's a way to switch between components with the State Method. Is it true?

In this Ruby on Rails app we work with one parent component and inside of it a lot of const components. The thing is, I have three buttons that the user needs to click, and when it does, a content block must change.

Any ideas?

Andrew Sunset
  • 39
  • 2
  • 12

1 Answers1

1

Sure, it's not optimal but I would definitely investigate why you can't use the React router. Try opening up another question and solving that issue.

import HomeComponent from 'home-component';
import AboutComponent from 'about-component';

const ROUTES = {
  home: HomeComponent,
  about: AboutComponent
};

class MainComponent extends Component {
  state = { component: HomeComponent }

  changeRoute = (routeName) => {
    this.setState({ component: ROUTES[routeName] || HomeComponent });
  }

  render() {
     const { component } = this.state;

     return (
       <div>
         <button onClick={() => changeRoute('home')}>Home</button>
         <button onClick={() => changeRoute('about')}>About</button>
         { component }
       </div>
     );
  }
}

This isn't a great approach, and clearly, the complexity will increase rapidly, but it may work for a small app.

Josh Alexy
  • 401
  • 1
  • 3
  • 13