Search code examples
javascriptreactjsaws-amplify

How to Use AWS Amplify react components anywhere in an application


I'm using aws-amplify and aws-amplify-react in my react application and I'm facing an authentication UI challenge that seems simple but I can't figure it out. Here is my App.js:

class App extends Component {
  render() {
    return (
      <Authenticator hideDefault={true}>
        <Router>
          <MyProvider>
            <Routes />
            <NavbarBot />
          </MyProvider>
        </Router>
      </Authenticator>
    );
  }
}

As you can see, I've hidden the React authentication components that comes with Authenticator. However, I want to use them in a child component (Accounts) nested in one of my Routes.

Here are my Routes:

const paths = () =>{
    return(
        <Switch>
            <Route path="/" exact component={Splash} />
            <Route path="/home" component={Home} />
            <Route path="/listing" component={Listing} />
            <Route path="/account" component={Account} />
            <Route component={NotFound} />
        </Switch>
        )
    };

const Routes =  withRouter(paths);

My Account component is blank. I tried importing the individual components like SignIn, SiginUp, and Greetings from aws-amplify-react and use them as jsx elements (e.g <SignIn />) but that doesn't render anything. Do I have to instantiate these components directly within the <Authenticator> component in my App.js? Do I have to pass down the components as props to my Accounts component? If so, is there a painless way to do so?

Maybe I am missing something, any help would be appreciated.


Solution

  • If you only want Authentication on the accounts page then you don't have to use Authenticator in the App component. Remove it and instead import { withAuthenticator } from 'aws-amplify-react'; directly inside the accounts page and wrap the account page export as export default withAuthenticator(Account);

    This will give you all the UI components you need only inside the accounts page. Change the account export to export default withAuthenticator(Account, {includeGreetings: true}); to get a logout button as well. Other config options here

    If you want to build you own UI and integrate it then import auth instead import { Auth } from 'aws-amplify';, you don't get UI components but you can customise the behaviour however you want. More on how to use Auth in the docs here