Andrii Gorokhovskyi
Andrii Gorokhovskyi

Reputation: 35

Convert this JS snippet to React

I'm new to React, just to get the idea, how would you convert this snippet to React?

<div id="input" contenteditable></div>
        <button id="submit">Convert to kg!</button>
        <br>
        <div id="output"></div>


       <script>

        const button = document.querySelector('#submit');
        const input = document.querySelector('#input');


        function convert() {
            let x=input.textContent;

       if (isNaN(x)) 
           {
           alert("Must input numbers");
           return false;



           }  else {
                const pounds = document.querySelector('#input').textContent;

                let kg = pounds*0.45;
                document.querySelector('#output').innerHTML = pounds + " pounds is " + kg + " kg";
           }
            }



        button.addEventListener('click', convert);

        </script>

I transformed html to jsx

<div
    id="input"
    contentEditable
    style={{ width: "40%", border: "solid 1px black", margin: "20px}" }}
  />
  <button id="submit">Convert to kg!</button>
  <br />
  <div id="output" style={{ marginTop: 20 }} />
</div>

But, how to go about Javascript, no idea... Can someone give a direction maybe?

Upvotes: -1

Views: 205

Answers (3)

Gopinath
Gopinath

Reputation: 4937

Here are the 6 steps for implementing the React component as per the above requirement:

  1. Define a React Component called App, which extends React Component.

  2. Initialize the 'state' of the component in the constructor method of the component.
    The state will contain the variables (weightLb, weightKg)

  3. Define a method (setWeightLb) to change the value of weightLb

  4. Define a method (convert) to calculate weightKg using the formula of

    kg = lb x 0.453592

  5. Define 'render' method to show static html of thecomponent

  6. Inside the render method, make calls to setWeightLb and convert on corresponding events.

Here is the working example:

import React, { Component } from "react"

export default class App extends Component {

  constructor(props) {
    super(props)
    this.state = {weightLb: 0.0, weightKg: 0.0}
  }    

  setWeightLb = (value) => {
    this.setState({weightLb: value})
  }

  convert = () => {
    this.setState({weightKg: (this.state.weightLb * 0.453592)})
  }

  render() {
    return (
      <div>
        <label>
          Pounds
          <input type="number" onChange={e => this.setWeightLb(e.target.value)} />
        </label>
        <button type="button" onClick={this.convert}>
          Convert to kg!
        </button>
        <div>Weight (kg): {this.state.weightKg}</div>
      </div>
    )
  }
}

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202608

Basic functional component:

  • weightLb state variable to hold user input
  • weightKg state variable to hold converted weight

component & logic:

function App() {
  const [weightLb, setWeightLb] = useState(0);
  const [weightKg, setWeightKg] = useState(0);

  const convert = () => {
    if (Number.isNaN(weightLb)) {
      alert("Must input numbers");
    }
    setWeightKg(weightLb * 0.45);
  }

  return (
    <div className="App">
      <label>
        Pounds
        <input type="number" onChange={e => setWeightLb(e.target.value)} />
      </label>
      <button type="button" onClick={convert}>Convert to kg!</button>
      <div>Weight (kg): {weightKg}</div>
    </div>
  );
}

Edit aged-hill-06911

Note: I didn't apply any styling other than default in sandbox.

A simpler abstraction may be to forego the button to convert and just convert input onChange on the fly; requires single piece of state.

function App() {
  const [weightLb, setWeightLb] = useState(0);

  const convert = () => {
    if (Number.isNaN(weightLb)) {
      alert("Must input numbers");
    }
    return weightLb * 0.45;
  };

  return (
    <div className="App">
      <label>
        Pounds
        <input type="number" onChange={e => setWeightLb(e.target.value)} />
      </label>
      <div>Weight (kg): {convert()}</div>
    </div>
  );
}

Upvotes: 1

user8737957
user8737957

Reputation:

Something like this. It may not work as you wished but from this example you can easly create your own answer i guess.


import React from "react";

const convert = (text) => {
  if (parseInt(text, 10) > 0) {
    const kg = parseInt(text, 10) * 0.45;
    document.querySelector("#output").innerHTML =
      text + " pounds is " + kg + " kg";
  }
  alert("You must enter digits");
};

const ExampleComponent = () => {
  const [text, setText] = React.useState("");

  return (
    <section>
      <div id="input" onChange={(e) => setText(e.target)}></div>
      <button id="submit" onClick={() => convert(text)}>
        Convert to kg!
      </button>
      <br />
      <div id="output"> </div>
    </section>
  );
};



Upvotes: 0

Related Questions