Search code examples
javascriptreactjsreact-routerreact-reduxreact-router-redux

call a component function from header componet in react router


Her is my index.js file, layout(header, middel-container, footer)

<div>
  <Header />
  <div className="middle-container">
    <Route path="/hello" component={HelloWorldApp} />
    <Route exact path="/" component={Login} />
  </div>
  <Footer />
</div>

I have separate file for Header, HelloWorldApp, Login and footer. On my Header component there have login button, if I click on login button it will call a function on Login component.

How I can I do that. (This is not a child, parent component so that I can pass the function name as props.)

Please help me.


Solution

  • Import {Link} from react-router-dom in your login component. Add a Link to "/" like **abc. If you want to call a method inside the login component(That way it should be a class component..) then You should instead try to add that state of login component in your index.js component and then you can call login stateless functional component by sending the state as props to it so you can get the desire results. Here is an example of calling a stateless functional component:

    login({[your_state_as_props]})=>
                 return([conclusion of your operations on props..]);
    

    further more you can read here https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17 and if you want to pass to data between two totally separate components,(HelloWorlApp and Login) then you can... but it will totally mess up all of your program. Instead hold any data that you require to send down to child components in your topmost component or make Helloworld component a method of your main component if its a functional component or if not, try to hold it's state in your topmost component and make helloworld a method of of your first component.