0

I'm developing a project, and when typing a value in one field, I need the other field to be changed based on the values ​​I defined in a function, here is the code:

constructor(props) {
    super(props);
    this.state = {
        yieldMonth: '',
        risk: '',

    }


}

changeYieldMonthHandler= (event) => {
    this.setState({yieldMonth: event.target.value});
}

changeRiskHandler= (event) => {
    this.setState({risk: event.target.value});
}

In the function below, I check the amount that will be inserted in the Monthly Income field, which should impact the risk field:

definesRisk(){
    if (this.state.yieldMonth != null){
        if (this.state.yieldMonth > 6000){
            this.state.risk= "A";
        } else if (this.state.yieldMonth > 1000 && this.state.yieldMonth <= 8000){
            this.state.risk = "B";
        } else {
            this.state.risk = "C";
        }
    }
}

And here is my render, where it should be updated dynamically according to the value of the field Monthly income. I'm trying to do it that way, does anyone help me know where I'm going wrong?

render() {
        return (
            <div>

                                <div className="form-group">
                                    <label> Yield Month: </label>
                                    <input type ="Number" placeholder="Yield Month:" name="yieldMonth" className="form-control"
                                    value={this.state.yieldMonth} onChange={this.changeYieldMonthHandler} onBlur={this.definesRisk} />
                                </div>

                                <div className="form-group">
                                    <label> Risk: </label>
                                    <input disabled type ="Number" placeholder="" name="risk" className="form-control"
                                           value={this.state.risk} onChange={this.definesRisk()} />
                                </div>
                            </form>
                        </div>

                    </div>
                </div>


            </div>
        )
    }
2
  • 5
    You are mutating the state directly this.state.risk= "A";. You should always use setState to change the state. this.setState({risk: 'A'}) Commented Dec 14, 2020 at 21:37
  • @RinkeshGolwala thank you so much man, problem fixed! Commented Dec 14, 2020 at 22:17

1 Answer 1

2

There is a big problem here:

The way that you're updating the state.this.state.risk='A' is not the correct way, instead you should call the setState method like this this.setState({risk:'A'})

definesRisk(){
    if (this.state.yieldMonth){
        if (this.state.yieldMonth > 6000){
            this.setState({risk:'A'});
        } else if (this.state.yieldMonth > 1000 && this.state.yieldMonth <= 8000){
           this.setState({risk:'B'});
        } else {
           this.setState({risk:'C'});
        }
    }
}

Also you had a closing form tag without an opening form tag.

Your code using class based components:

import React, { Component } from "react";
import "./styles.css";

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      yieldMonth: "",
      risk: ""
    };
  }

  changeYieldMonthHandler = (event) => {
    this.setState({ yieldMonth: event.target.value });
  };

  definesRisk() {
    if (this.state.yieldMonth > 6000) {
      this.setState({ risk: "A" });
    } else if (this.state.yieldMonth > 1000 && this.state.yieldMonth <= 8000) {
      this.setState({ risk: "B" });
    } else {
      this.setState({ risk: "B" });
    }
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (prevState.yieldMonth !== this.state.yieldMonth) {
      this.definesRisk();
    }
  }

  render() {
    return (
      <div>
        <form>
          <div className="form-group">
            <label> Yield Month: </label>
            <input
              type="Number"
              placeholder="Yield Month:"
              name="yieldMonth"
              className="form-control"
              value={this.state.yieldMonth}
              onChange={this.changeYieldMonthHandler}
            />
          </div>

          <div className="form-group">
            <label> Risk: </label>
            <input
              disabled
              type="text"
              placeholder=""
              name="risk"
              className="form-control"
              value={this.state.risk}
            />
          </div>
        </form>
      </div>
    );
  }
}

Notice that in order to call your definesRisk methode whenever the state updates i've used componentDidUpate lifecycle method

Here is your your code using react functionnal components with hooks :

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [yieldMonth, setYieldMonth] = useState("");
  const [risk, setRisk] = useState("jkkkj");

  const changeYieldMonthHandler = (event) => {
    setYieldMonth(event.target.value);
  };

  useEffect(() => {
    const definesRisk = () => {
      if (yieldMonth > 6000) {
        setRisk("A");
      } else if (yieldMonth > 1000 && yieldMonth <= 8000) {
        setRisk("B");
      } else {
        setRisk("C");
      }
    };
    definesRisk();
  }, [yieldMonth]);

  return (
    <div>
      <form>
        <div className="form-group">
          <label> Yield Month: </label>
          <input
            type="Number"
            placeholder="Yield Month:"
            name="yieldMonth"
            className="form-control"
            value={yieldMonth}
            onChange={changeYieldMonthHandler}
          />
        </div>

        <div className="form-group">
          <label> Risk: </label>
          <input
            disabled
            type="text"
            placeholder=""
            name="risk"
            className="form-control"
            value={risk}
          />
        </div>
      </form>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.