CryptoRank Exchange

  • + 0 comments
    	import React, { useState } from "react";
    import Table from "./Table";
    
    const availableBalance = 17042.67;
    
    const errorChecks = [
      [(amount) => !amount, "Amount cannot be empty"],
      [(amount) => amount < 0.01, "Amount cannot be less than $0.01"],
      [(amount) => amount > availableBalance, "Amount cannot exceed the available balance"],
    ]
    
    function Main() {
      const [inputAmount, setInputAmount] = useState('');
      const [errorMessage, setErrorMessage] = useState('');
    
      const handleChange = (e) => {
        const error = errorChecks.find(([condition,]) => condition(+e.target.value))
        setErrorMessage(!error ? '' : error[1])
        setInputAmount(e.target.value);
      }
    
      return (
        <div className="layout-column align-items-center mx-auto">
          <h1>CryptoRank Exchange</h1>
          <section>
            <div className="card-text layout-column align-items-center mt-12 px-8 flex text-center">
              <label>
                I want to exchange $ <input className="w-10" data-testid="amount-input" required type="number" placeholder="USD" value={inputAmount} onChange={handleChange} /> of my $
                <span>{availableBalance}</span>:
              </label>
              {errorMessage && <p data-testid="error" className="form-hint error-text mt-3 pl-0 ml-0">
                {errorMessage}
              </p>}
            </div>
          </section>
          <Table inputAmount={inputAmount} errorMessage={errorMessage}/>
        </div>
      );
    }
     export default Main;
    
    import React from "react";
    import { cryptocurrencyList } from "../cryptocurrency-list";
    
    function Table({inputAmount, errorMessage}) {
      return (
        <div className="card card-text mt-10 mx-4">
          <table className="mb-0">
            <thead>
              <tr>
                <th>Cryptocurrency</th>
                <th>Exchange Rate</th>
                <th>Number of Coins</th>
              </tr>
            </thead>
            <tbody data-testid="exchange-data">
              {cryptocurrencyList.map(({code, name, rate}) => (
                <tr key={code}>
                  <td>{name}</td>
                  <td>1 USD = {`${rate} ${code}`}</td>
                  <td>{!inputAmount ? `0.00000000` : errorMessage ? 'n/a' : `${(inputAmount * rate).toFixed(8)}`}</td>
              </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    
    export default Table;
    `
    export default Main;
    
    -------------