YogeshChauhan . com

Create a currency (dollar) to coins convertor in React

in React on May 30, 2021

The basic idea of this post to explore a concert called “lifting state up” using which we can update two different elements states at the same time.

When you want to update the two fields at the same time, React recommends lifting the shared state of the components to their common ancestor.

Let’s understand this by an example where we need to change the data for two different elements at the same time on some event.

Let’s create a component that basically checks if you’re a millionaire in yCoins! Sorry for the cheeky name, Yogesh Coins == yCoins!

With just simple if-else, it will just evaluate a condition and respond based on that.

Let’s call that component MillionaireCheck. It accepts yCoins variable as prop and returns whether you have enough yCoins to become millionaire.


function MillionaireCheck(props) {
  if (props.yCoins >= 1000000) {
    return <p>You are a yCoins Millionaire!</p>;
  } else {
    return (
      <p>
        You still need {1000000 - props.yCoins} more to become a Millionaire in
        yCoins!
      </p>
    );
  }
}


Now, let’s create another component and name it Currency where an user can enter the yCoins they have and the component will render MillionaireCheck component for the input value entered by the user.

Add another input element

What we want to do is give users another input field to enter dollars and we’ll convert them to yCoins in real time.

Let’s add the currencies props at the top and extract the CurrencyInput component from Currency.


const currencySymbols = {
  d: "Dollar",
  y: "yCoins",
};

class CurrencyInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {currency: ''};
  }

  handleChange(e) {
    this.setState({currency: e.target.value});
  }

  render() {
    const currency = this.state.currency;
    const currencySymbol = this.props.currencySymbol;
    return (
      <fieldset>
        <legend>Enter Currency in {currencySymbols[currencySymbol]}:</legend>
        <input
          value={currency}
          onChange={this.handleChange} />
        <MillionaireCheck
          yCoins={parseFloat(currency)} />
      </fieldset>
    );
  }
}


Both of the inputs are working independently. Their values are not affected by each other at all.

We can now change the Calculator to render two separate CurrencyInput:


class Calculator extends React.Component {
  render() {
    return (
      <div>
        <CurrencyInput currencySymbol="d" />
        <CurrencyInput currencySymbol="y" />
      </div>
    );
  }
}


Give the gift of Audible

Currency Convertor Functions

Let’s create the functions to convert yCoins into Dollars and vice versa.


function toDollar(yCoins) {
  return yCoins / 100;
}

function toYCoins(dollar) {
  return dollar * 100;
}

Let’s write another function to pass a currency in string and a convertor function. It will return a string. The function basically calculates one input’s value based on another.


function tryConvert(currency, convert) {
  const input = parseFloat(currency);
  if (Number.isNaN(input)) {
    return "";
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

The function above will return an empty string on invalid currency entry and it will keep it rounded to two decimal places.

We won’t require that function in our setup as the exchange rate is integer only but this function will be helpful if you want to change a single digit in the conversion.

What is Lifting State Up?

We want to show the yCoins and Dollars conversion in real time. So, when a user enters yCoins, the Dollars input will be updated and vice versa.

Lifting state up is nothing but a term for sharing a state for multiple components by moving it up to their closest ancestor.

So, let’s remove the state from CurrencyInput component and move it to Currency component instead.

If the Currency component owns the shared state then it will become the source of truth. In that way it can tell both of those components to have their values in sync. The props of both of the CurrencyInput components are coming from the Currency component and that’s how it will always be in sync.

To do so, we need to replace this.state.currency with this.props.currency in CurrencyInput component.

Props are read-only in React. The currency is provided by the common parent as a prop so CurrencyInput component can not control it. If you want to give CurrencyInput component control and make it a controlled component.

The CurrencyInput accepts both currency and onCurrencyChange props from its parent component, Currency.

When the CurrencyInput wants to update its currency, it calls this.props.onCurrencyChange.

Credit for this post goes to React Docs.

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

The order Property in Flex Items in CSSCSSWhat is Host Hardening and What are some Important Hardening Steps?MiscOptional arguments, Default parameters and REST parameters in JavaScriptJavaScriptHow to Skip or Exclude a Specific URL or File From .htaccess Rewrite Rule?PHPHow to create Glowing Text using CSS?CSSHow to use @if and @else in SCSS?SCSS