Home > OS >  React - Pass form values as props during onclick
React - Pass form values as props during onclick

Time:06-14

I am new to React JS, I am practicing React JS through online react problems. In one of the problem I got a below requirements.

Task Description:

  • Step 1: The form should consists of two input Fields: once for username and one for dob. Each input should update it's value attribute on input change.

  • Step 2: There should also be a submit button. It should call the onSubmit handler when clicked.

  • Step 3: The onsubmit hanlder is passed through the props to the component and accepts two parameters(username and dob).

  • Step 4: When the submit button is clicked, onSubmit handler should be called. Use a button click event handler for this purpose.

  • Req 1: Create an input element for username field and dob field.

  • Req 2: Both the input should update it's value attribute on being changed with entered input.

  • Req 3: Create a submit button.

  • Req 4: The submit button should be disabled until both username and dob fields are filled.

  • Req 5: The onsubmit handler should be called when the submit button is clicked.

  • Req 6: The onsubmit handler should be called with the username and dob passed as parameters.

Above is the task I am trying to execute. In the above steps and requirements, I have completed (step: 1, step: 2, step: 4) in requirement I have completed till (Req: 5). I coudln't able to understand the Step 3 and Req 6. I have wrote down the code for all requirements except Requirement 6. Could any one please help me to achieve the requirement 6.

  export default function UserData() {
      const intialValues = {
        userName: "",
        dob: "",
      };
    
      const [values, setValues] = useState(intialValues);
    
      const handleInputChange = (e) => {
        const { name, value } = e.target;
        console.log("first", name);
    
        setValues({
          ...values,
          [name]: value,
        });
      };
    
      const onsubmitHandler = (e) => {
        console.log("Clicked");
        console.log({ ...values });
      };
    
      return (
        <div>
          <form>
            <input
              value={values.userName}
              onChange={handleInputChange}
              name="userName"
              label="Username"
            />
    
            <input
              value={values.dob}
              onChange={handleInputChange}
              name="dob"
              label="DOB"
            />
    
            <button
              type="button"
              disabled={!values.userName || !values.dob}
              onClick={onsubmitHandler}
            >
              Submit
            </button>
          </form>
        </div>
      );
    }

CodePudding user response:

am not sure why do you want to pass form values as params to handle submit because in normal case you are able to access state but yeah you can do something like this for passing params.

onClick={() => onsubmitHandler(values)}

CodePudding user response:

If I am not mistakne, than you are trying to pass the state as agruments throguht the onsubmitHandler function. If you want to pass arguments to an event handler in react, you have to use an arrow function like that : onClick={() => function(arg1, ...)}. This is because onClick expects a function reference which can be called if the onClick Event Handler has been triggerd. If you pass a function directly into the onClick Event Handler like that onClick{function(arg1, ...)} the function runs and gets replaced with its returned value, so onClick{function(arg1, ...)} becomes onClick{whatever_the_function_returned}

const {useState} = React;

function UserData() {
  const intialValues = {
    userName: "",
    dob: "",
  };

  const [values, setValues] = useState(intialValues);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    console.log("first", name);

    setValues({
      ...values,
      [name]: value,
    });
  };

  const onsubmitHandler = (a, b) => {
    console.log("Clicked");
    console.log(a, b);
  };

  return (
    <div>
      <form>
        <input
          value={values.userName}
          onChange={handleInputChange}
          name="userName"
          label="Username"
        />

        <input
          value={values.dob}
          onChange={handleInputChange}
          name="dob"
          label="DOB"
        />

        <button
          type="button"
          disabled={!values.userName || !values.dob}
          onClick={() => onsubmitHandler(values.userName, values.dob)}
        >
          Submit
        </button>
      </form>
    </div>
  );
}


ReactDOM.render(
    <UserData />,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

  • Related