Step 6
Let's update the app, so when a user clicks on the + button, we navigate to the /add page. Moreover, when a user clicks on the cancel button on the AddNote component, we return to the homepage.
Open the DisplayNotes.js file and import the following:
import { Link } from "react-router-dom";
Delete the onClick event handler along with any notion of changePage prop. Next, wrap the Fab component in the Link component.
<Link to="/add">
<Fab aria-label={"Add"} className={classes.fab}>
<Add />
</Fab>
</Link>
The Link component is similar to the HTML anchor element (
<a>).
Notice the to props which recieves a page's pathname to navigate to. You can do many interesting things with the <Link> component; please consult the documentation.
Next, open the AddNote.js file and import the following:
import { withRouter } from "react-router";
The withRouter is a higher-order component. Update the export statement as follows:
export default withRouter(AddNote);
The withRouter attaches a history object to the AddNote props. Extract it from the props object and use it to navigate to the homepage.
function AddNote(props) {
- const { changePage } = props;
+ const { history } = props;
const handleCancel = (event) => {
event.preventDefault();
- changePage();
+ history.push("/");
}
// The return statement not shown to save space
}
The history is a JavaScript object that enables interaction with the browser history API. Please consult the documentation to learn more.
Save the files and revisit the React application. Try to use the + and "cancel" buttons to navigate to different pages
