Step 3
We can store a setting in the app state to switch between different "views."
Add the following variable to the state of the App
component:
this.state = {
+ showHomepage: true,
notes: [ /* Data not shown to save space */ ]
}
Next, add the following method to the App
component:
changePage = () => {
this.setState((state) => {
return {
showHomepage: !state.showHomepage,
};
});
};
Then, update the App.render
method:
render() {
const { notes, showHomepage } = this.state;
return (
<Container>
{showHomepage ? (
<DisplayNotes
notes={notes}
deleteNote={this.deleteNote}
changePage={this.changePage}
/>
) : (
<AddNote changePage={this.changePage} />
)}
</Container>
);
}
Notice how the showHomepage
is used to "switch" between <DisplayNotes />
and <AddNote />
.
Moreover, note we pass the changePage
method to both DisplayNotes
and AddNote
components as props.
Update the DisplayNotes
component as follows:
function DisplayNotes(props) {
- const { notes, deleteNote, classes } = props;
+ const { notes, deleteNote, classes, changePage } = props;
return (
<>
<List>
{notes.map((note, index) => {
return <Note note={note} key={index} deleteNote={deleteNote} />;
})}
</List>
- <Fab aria-label={"Add"} className={classes.fab} >
+ <Fab
+ aria-label={"Add"}
+ className={classes.fab}
+ onClick={() => changePage()}
+ >
<Add />
</Fab>
</>
);
}
Update the AddNote
component as follows:
- function AddNote() {
+ function AddNote(props) {
+ const { changePage } = props;
+
+ const handleCancel = (event) => {
+ event.preventDefault();
+ changePage();
+ }
+
return (
<form>
<FormControl fullWidth>
<TextField label="Title" variant="outlined" />
</FormControl>
<FormControl fullWidth>
<TextField label="Text" multiline rows={4} variant="outlined" />
</FormControl>
<div>
- <Button type="button" color="secondary" >
+ <Button type="button" color="secondary" onClick={handleCancel}>
Cancel
</Button>
<Button type="submit" color="primary">
Submit
</Button>
</div>
</form>
);
}
Save the files and revisit the React app: