Customising Cognito SignIn UI for aws-amplify-react with TypeScript
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: AWS Cognito, aws-amplify-react, React, TypeScript
Let’s assume you are having trouble with customising Cognito Sign In UI for aws-amplify-react with TypeScript and have already know what AWS Cognito, aws-amplify and aws-amplify-react.
Customising Cogito Signin UI is easy with JavaScript React. All you need to do is to extend the SignIn class in aws-amplify-react with a new showComponent method returning your customised UI. Here is the official documentation on Cognito Authentication for React. There is an excellent blog post that explains how to extend SignIn class here.
If you are into plain JavaScript without any framework, check out this post, Serverless Authentication with AWS Cognito and JavaScript.
Using aws-amplify-react with TypeScript requires a little bit more effort because the library does not offer types and you have to provide your own for customisation. It is surprising that aws-amplifiy is written in TypeScript, yet aws-amplify-react is only written in JavaScript and has no support for TypeScript (although this is likely to be changed in the future considering the popularity and benefits of developing application with TypeScript).
When you first use aws-amplify-react with TypeScript, you need to declare module to get it work as below (the file can be called as aws-amplify-react.d.ts in the types folder).
declare module 'aws-amplify-react';
To customise anything in that library, you need to provide more detailed type. Here is the example for customising SignIn page. Basically, any type error you get, you add that class, variable or function in this file.
Now, you can have your custom sign page by extending SignIn class.
The authState is passed down to the child component. You can return your UI when authState is ‘signedIn’.
Now wrap this in Authenticator with the CustomSignIn component we created. The authState will be available in the App component.
Then, use AppWithAuth component in the index.tsx.
That’s it!
By the way, if you are having an error below, all you need to do is set NODE_ENV=production. It will stop doing the unnecessary package checking and error will disappear.
bundle.js:1442 Uncaught Error: Cannot use e "__Schema" from another module or realm. Ensure that there is only one instance of "graphql" in the node_modules directory. If different versions of "graphql" are the dependencies of other relied on modules, use "resolutions" to ensure only one version is installed. https://yarnpkg.com/en/docs/selective-version-resolutions Duplicate "graphql" modules cannot be used at the same time since different versions may have different capabilities and behavior. The data from one version used in the function from another could produce confusing and spurious results.