React throwaway app 1: Currency Converter 
Tags: beginners, react, webdev
Published: 2018-07-02 15:45:17

---
title: React throwaway app 1: Currency Converter 
published: true
description: An app to show your basic understanding of React
tags: #beginners,#react,#webdev
---

## Intro
Sometime last year, i came across an [article](https://daveceddia.com/timeline-for-learning-react/) written by Dave Ceddia on how to learn React.
He clearly stated the order of what to learn while on your learning journey.

I liked his idea of building a few things after learning pure React and throwinng them away; step 2 from the article.
This was a good idea because the problem with taking courses and reading programming books straight to the end is that you feel you know and understand the concepts covered. I'm sorry, you dont, not until you've fired up your favorite code editor and build stuffs based of what you've learnt. 

It is very easy for new developers to fall into [**tutorial purgatory**](https://dev.to/tonymastrorio/escaping-tutorial-purgatory-as-a-new-developer-1kf3). This simply means consuming so much tutorials and never feeling you have learnt enough to build stuffs.

## Do you think you know React?
In this series, we our going to test ourselves to see if we could build small '**throwaway projects**' to show that we understand and think in React.
Knowing a concept is one thing. Knowing how to combine this knowledge and when to use them in another.

## What are we going to achieve
You are going to build '**throwaway app**' that shows you think in react and understand its basic concepts. This series would cover about 6 apps (you could suggest more throwaway apps because i cant think of more right now).

The apps you are going to build in this series:
1. Currency Converter
2. [Movie Search](https://dev.to/fleepgeek/react-throwaway-app-2-movie-search-app-3f3d)
3. ....would think of more as we progress

## The Rules
- Your app should be completed within 60 minutes.
- Must be pure React (no react-router or redux).
- Must delete the project after one week. Why? These are basic apps you should be able to build anytime and not worthy of showcasing as a portfolio for a serious job interview.
- Don't spend much time on designing. Remember, the idea is to check if you think in React. You could style to your taste after 60 minutes.
- Don't look at my solution until you have completed yours. Else, you would be struck with 5 years of 'tutorial purgatory'

## App 1: Currency Converter
You are to build a currency converter.
Here is a screenshot:

![Converter screenshot](https://thepracticaldev.s3.amazonaws.com/i/39e5ho0vdsgbfb3uqxja.PNG)
You could use the free api provided by [OpenRates.io](http://www.openrates.io/)
This app would show that you understand how:
- components and states work
- to request data from an api
- component life cycle methods
- to use events

###Your time starts now!!

## My Solution
I used the the OpenRates api to get my exchanges rates and create-react-app to generate a base structure for my project. Also, i used 'axios' to handle my requests.
Here is my diectory structure for the Converter component:

![directory structure](https://thepracticaldev.s3.amazonaws.com/i/bd152b7vxejao50ht1i4.PNG)

Here is the complete Converter.js 


```jsx
import React, { Component } from "react";
import axios from "axios";

import './Converter.css';

class Converter extends Component {
    state = {
        result: null,
        fromCurrency: "USD",
        toCurrency: "GBP",
        amount: 1,
        currencies: [],
    };

    // Initializes the currencies with values from the api
    componentDidMount() {
        axios
            .get("http://api.openrates.io/latest")
            .then(response => {
                // Initialized with 'EUR' because the base currency is 'EUR'
                // and it is not included in the response
                const currencyAr = ["EUR"]
                for (const key in response.data.rates) {
                    currencyAr.push(key)
                }
                this.setState({ currencies: currencyAr.sort() })
            })
            .catch(err => {
                console.log("Opps", err.message);
            });
    }

    // Event handler for the conversion
    convertHandler = () => {
        if (this.state.fromCurrency !== this.state.toCurrency) {
            axios
                .get(`http://api.openrates.io/latest?base=${this.state.fromCurrency}&symbols=${this.state.toCurrency}`)
                .then(response => {
                    const result = this.state.amount * (response.data.rates[this.state.toCurrency]);
                    this.setState({ result: result.toFixed(5) })
                })
                .catch(err => {
                    console.log("Opps", err.message);
                });
        } else {
            this.setState({ result: "You cant convert the same currency!" })
        }
    };

    // Updates the states based on the dropdown that was changed
    selectHandler = (event) => {
        if (event.target.name === "from") {
            this.setState({ fromCurrency: event.target.value })
        }
        if (event.target.name === "to") {
            this.setState({ toCurrency: event.target.value })
        }
    }

    render() {
        return (
            <div className="Converter">
                <h2><span>Currency </span> Converter <span role="img" aria-label="money">&#x1f4b5;</span> </h2>
                <div className="Form">
                    <input
                        name="amount"
                        type="text"
                        value={this.state.amount}
                        onChange={event =>
                            this.setState({ amount: event.target.value })
                        }
                    />
                    <select
                        name="from"
                        onChange={(event) => this.selectHandler(event)}
                        value={this.state.fromCurrency}
                    >
                        {this.state.currencies.map(cur => (
                            <option key={cur}>{cur}</option>
                        ))}
                    </select>
                    <select
                        name="to"
                        onChange={(event) => this.selectHandler(event)}
                        value={this.state.toCurrency}
                    >
                        {this.state.currencies.map(cur => (
                            <option key={cur}>{cur}</option>
                        ))}
                    </select>
                    <button onClick={this.convertHandler}>Convert</button>
                </div>
                {this.state.result && 
                    <h3>{this.state.result}</h3>
                }
            </div>
        );
    }
}

export default Converter;

```

I wouldn't go into details of the above code because i believe you already know React (that's why you started reading this article in the first place, right?) but i would give an overview of what's happenning.

The list of currencies is initialized in the `componentDidMount()`. The values are gotten from the OpenRates API and would be used to populate our drop-downs.
The `convertHandler()` is where the conversion takes place and it is triggered by the `onClick` event of the button.
Also, i have a `selectHandler()` which is shared by the two drop-downs. This function conditionally updates the state based on which drop-down was changed (that was why i gave the drop-downs `name` attribute ). You could call this **Conditional Shared Events** if you're into giving every concept names.
You could definitely perform an inline event trigger on the drop-downs like i did for the input text field, i just showed that we could have one event handler shared by different similar components.
Finally, i import the `Converter` component inside of my App.js file and i call it inside its `render` function.


```jsx
//This is also correct
onChange={(event) => this.setState({ fromCurrency: event.target.value })}
```


Here is the css: **Converter.css**
```css
.Converter {
    width: 100%;
    padding: 0 15%;
    box-sizing: border-box; 
    text-align: center;
}

.Form {
    display: flex;
    margin: 0 auto;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    width: 100%;
}

.Form input, select {
    padding: 5px;
    margin: 5px 10px;
    border-radius: 5px;
    border: 1px solid rgba(119, 119, 119, 0.5);
}

.Form button {
    padding: 5px 10px;
    border-radius: 5px;
    background: rgb(11, 170, 59);
    color: white;
    border: none;
}

.Converter h3 {
    background-color: #ccc;
    border-radius: 10px;
    padding: 15px;
    font-size: 30px;
}

.Converter h2 span {
    color: rgb(11, 170, 59);
}
```

## Conclusion
I hope this was a good exercise and you enjoyed it? 
If you coded the app successfully without looking at mine: Well Done.
If you couldn't: Well Done too. It shows that you're eager to challenge yourself and that is a good attribute of a developer. With time, you'll understand these concepts.

Remember, we always have to test our knowledge constantly as developers and i hoped this simple exercise helped. 
See you tomorrow for the next '**throwaway app**' challenge. Thanks for reading!!

Link to the next throwaway app: [Movie Search](https://dev.to/fleepgeek/react-throwaway-app-2-movie-search-app-3f3d)