Create an app that displays and updates data via a Context provider and consumers.
- React
- Components and State
- React Context
- Create a new app with
npx create-react-app react-context-lab
. - Switch into the new project directory with
cd react-context-lab
. - Open the project in VS Code with
code .
. - Complete the requirements listed below.
- Create a file in your
src
directory called UserContext.js and useexport const UserContext = React.createContext(null);
to create a provider and consumer for your app. - Your App component should render a Header component and a Home component. Create some state there for your user object. Give it an initial state of:
{ username: '', lastLogIn: '' }
- Add a
UserContext.Provider
component to App that will wrap all of the components that App renders. - The Header component should render a Login component.
- The Login component should contain a form element that has one text input for the
username
and a submit button. When the form is submitted, it should use the Context consumer to update the user in context with an object that contains the username property and the current date and time such as:{ username: 'username-here', lastLogIn: 'current-date-time' }
. - The Login component should also have a separate 'logout' button, that when clicked sets the user object to:
{ username: '', lastLogIn: '' }
- On the Home component, display either a message that reads: Welcome Back username. You logged in at lastLogIn. or a message that reads: Welcome, please login.
- Use moment to format the date and time.
- Show the login form only when there is no user and the logout button only when the user is logged in.