Chris
Chris

Reputation: 117

React toggle global Component

I got all my Routes in my App.js like this:

<Route exact path="/" component={Home} />
<Route path="/explore" component={Explore} />
<Route path="/register" component={Register} />
<ProtectedRoute path="/create" component={CreatePost} />

and I want to toggle an Success/Error Alert Component as Feedback but I want to display it above the whole app no matter which component is rendered right now. So I am stuck and don't know what is the best way to do so. I tried to write a function to toggle the Alert in App.js and export it but it didn't work for me to import it and change the state.

 onShowAlert = () => {
    this.setState({ showAlert: true };
  };

Upvotes: 0

Views: 287

Answers (2)

Pavlos Karalis
Pavlos Karalis

Reputation: 2976

If you're trying to avoid passing the toggler as a prop, then create an AlertContext: https://codesandbox.io/s/great-moon-93c94?file=/src/AlertContext.js

Upvotes: 1

Dmitriy Godlevski
Dmitriy Godlevski

Reputation: 620

You can use render assignment and pass your feedback trigger to the component. Is this what you are asking?

function myTigger(){ console.log('triggered') }

<Route exact path="/" render={ () => <Home trigger={myTigger} />} />
<Route path="/explore" component={Explore} />
<Route path="/register" component={Register} />
<ProtectedRoute path="/create" component={CreatePost} /

Upvotes: 1

Related Questions