My Research: Learning ReactJS – Part Two – React Router + Searching

Note: You may want to checkout My Research: Learning ReactJS – Part One first.

Going into this I thought React was going to be awful if I am completely honest, but it turns out it’s not so bad after all. All of the data types feel nice and easy to work with, being that it is Javascript and there are a decent amount of modules and tutorials available to get me started with it.

So what have I actually achieved so far?

I have been working on a monster finder for Dungeons and Dragons 5th edition, using an open source API and it’s going pretty good so far. I have a lot more done than I expected I would of, with maybe 2 evenings worth of research and one evening in particular being the majority of the time I have spent on it. Here it is:

https://epicwebs.co.uk/react/

You will notice that if you click a monster link and then refresh it errors, this is fixed with a htaccess redirect but I haven’t bothered to do that yet, I’ll do it at some point.

A list of what I have actually done:

  • I have managed to pull in data from the API and have a list of that data down the left hand side (on desktop).
  • I pulled in this module: https://www.npmjs.com/package/react-search-input, which was really easy to setup and get working. The only thing that took me longer than expected was being able to add a class to the input, which is the inputClassName prop, it seems really obvious but I didn’t find it in the link above anywhere.
  • Next I added the react-router-dom module from: https://www.npmjs.com/package/react-router-dom. This was what took the majority of the time for me, initially I couldn’t get it working with a separate Monster component but I have now got it working and it’s pretty awesome. You effectively just need to get the props.match.params plus the name of the ID you have given the route inside your component.
 componentWillReceiveProps(props) {
this.state.monsterId = props.match.params.monsterId;
  • The last step was to grab the correct data based on that ID and have it display on the right hand side, which was really easy after I setup the routing above.

Summing it all up!

All in all it’s been a lot easier than I first imagined, but I can guarantee my code isn’t as clean as it could be and I have a huge amount more to learn. Hopefully you find this useful and can follow along checking out the page above every so often, I may add the code to github so that you can see my versions as I go along, we shall see!

Useful resources

A really useful resource is the component life cycle docs which can be found here: https://github.com/ReactTraining/react-router/blob/c865bc6b331eabd853641dcc7e0224a7dce76f3b/docs/guides/ComponentLifecycle.md. This helped me understand how a React Component works a lot and was really interesting to read, I highly recommend just having a quick glance.

All the best
Rob.

Comments