Search code examples
reactjsmathuse-statemultiplicationobject-state

Math operation in React State


I want to display the input of % value. When I log this it showing properly but can't display in page.

Want to display the input of % value below the input section:

want to display the input of % value below the input section

const [rcommission, setRcommission] = useState({
    aeps: "",
    matm: "",
});

let name,value;
const getRetailData = (event) => {
    name= event.target.name;
    value= event.target.value;
    setRcommission({ ...rcommission, [name]:value });
    let aeps = Number(value);
    aeps *= 0.03;
    let matm = Number(value);
    matm *= 0.04;
    if (name === 'aeps') {
        console.log(aeps);
    } else if (name === 'matm') {
        console.log(matm);
    }
};

this is the input sec-

<input name="aeps"
            type="number"
            value={rcommission.aeps}
            onChange={getRetailData}
            id="ContentPlaceHolder1_txtname"
            className="form-control"
            autoComplete="off"
            placeholder=" AEPS" />

            <div className="help-block with-errors"></div>
        </div>
        <span> {rcommission.aeps} </span>

Solution

  • I don't know if is this what you need, but I can try help you. Check my code:

    const [rcommission, setRcommission] = useState({
          aeps: 0,
          matm: 0
    });
    
    const getRetailData = (event) => {
         const name = event.target.name;
         const value = event.target.value;
         setRcommission({
            ...rcommission,
            [name]: name === "aeps" ? value * 0.03 : value * 0.04,
         });
    };
    

    And this is my render:

    <div className="">
      <input
        name="aeps"
        type="number"
        onChange={getRetailData}
        id="ContentPlaceHolder1_txtname"
        className="form-control"
        autoComplete="off"
        placeholder=" AEPS"
      />
      <br />
      <br />
      <input
        name="matm"
        type="number"
        onChange={getRetailData}
        id="ContentPlaceHolder1_txtname"
        className="form-control"
        autoComplete="off"
        placeholder=" MATM"
      />
    
      <h5>AEPS: {rcommission.aeps} </h5>
      <h5>MATM: {rcommission.matm} </h5>
    </div>