Day 2: React Router, State and Props

#100DaysOfCode : Building a React App contd…

Project (1 Hour): Continue to build onto the app created on Day 1. Create three components and setup react-routing instructions for navigating between components. Model data with state and props.

All the code for this project can be found on my github

Step 1: Install react-router, history packages

npm install --save react-router history

React-router package has a dependency on history, so it needs to be installed as well.

Step 2: Update main and create home component

Create a component home.js as below and update main.js remove react-dom in components, instead it will be exported as a true component.

Code available in github repo link mentioned above.

Step 3: Create App Componet “app.js” in App directory

Here instead of passing in a component we use our router which handles all the routes in the application.

The first property “routes” here is an instruction sheet to router to decide which component to render based on which path we are at. The second property tells which element id to render it at.

Update webpack config to use App.js as the root component.

Step 4: Create router instruction sheet

Create a directory “config” inside “app” and add the following routes.js to it.

Setup a path in Router, so that whenever anyone goes to root path “/” in our app the component that they are going to get served is “Main”. The Main component here just renders Hello World at this point. Look at github repo for an updated one with three components rendered. Exporting instructions for router is in routes.js, which then goes to App.js, where it is received by the <Routes> tag. So whenever someone is at “/” home or index path then go ahead and render Main.js. Similarly we can setup routes for other params such as when url has “/profile/anyname” to give out Profile component.

Step 5: Create profile component with state and props

As you can see above, we have initial state filled with default values. Render specifies JSX tags to be displayed on view. Note how “this.props.params.username” is a field retrieved from url versus “this.state.bio” is something thats from the internal state that is initialized.

When everything is hooked up as per the code in github repo for Day 2, rerun webpack. Note you can skip re-running webpack if it is already running as it automatically recheck and retranspile.

webpack -w

Finally, the rendered out output when you add “/profile/TestUser” to the end of your URL, should look like the image below.

/ReactApp/public/index.html#/?_k=vodu5g/profile/TestUser

Day 2 of #100DaysOfCode DONE

If you enjoyed this, please click 👏 so that others can enjoy it as well. Follow me on Twitter @HariniLabs to get the latest updates or just to say Hi :)

PS: I curate a bi-weekly #WomenInTech newsletter for a dose of inspiration from the world of tech and yes men can signup too! Get it here :)