IWI
IWI

Reputation: 1608

How can I get a value from a React-Bootstrap form on submit?

I am trying to get the value of a form input using React-Bootstrap. What is the standard procedure to get the form value from a react bootstrap form on a functional component in react?

export default function SpouseForm() {
  const dispatch = useContext(DispatchContext);

  return (
    <Form>
      <Row>
        <Col xs={12} md={12} lg={{ span: 6, offset: 3 }}>
          <InputGroup className="mb-3">
            <InputGroup.Prepend>
              <InputGroup.Text>Age</InputGroup.Text>
            </InputGroup.Prepend>
            <FormControl /> <--------- I want to get this value on submit /////////////////
      </InputGroup>
        </Col>
      </Row>
      <Row>
        <Col xs={12} md={12} lg={{ span: 6, offset: 3 }}>
          <Button
            onClick={(e) => {
              e.preventDefault()
              dispatch({ type: "SPOUSE_AGE", spouseAge: e.target.value }); < ----- tried to get it here, not working
              router.push('/children')
            }}
            style={{ width: '100%' }}
            type="submit"
            variant="outline-primary"
            size="lg" >Next</Button>{' '}
        </Col>
      </Row>
    </Form>
  )
}

Upvotes: 13

Views: 27819

Answers (2)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

It's either you have controlled input and keep track of its value in real-time stored within your state:

const { useState } = React,
      { render } = ReactDOM,
      { Form , Button } = ReactBootstrap,
      rootNode = document.getElementById('root')

const App = () => {
  const [value, setValue] = useState(),
        onInput = ({target:{value}}) => setValue(value),
        onFormSubmit = e => {
          e.preventDefault()
          console.log(value)
          setValue()
        }
  
  return (
    <Form onSubmit={onFormSubmit}>
      <Form.Control 
        type="text" 
        onChange={onInput} 
        value={value}
      />
      <Button type="submit">
        Submit
      </Button>
    </Form>
  )
}

render (
  <App />,
  rootNode
)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"></script><div id="root"></div>

Or, the other way around, you have uncontrolled inputs and access FormData upon submit:

const { useState } = React,
      { render } = ReactDOM,
      { Form , Button } = ReactBootstrap,
      rootNode = document.getElementById('root')

const App = () => {
  const onFormSubmit = e => {
          e.preventDefault()
          const formData = new FormData(e.target),
                formDataObj = Object.fromEntries(formData.entries())
          console.log(formDataObj)
        }
  
  return (
    <Form onSubmit={onFormSubmit}>
      <Form.Control type="text" name="myInput" />
      <Button type="submit">
        Submit
      </Button>
    </Form>
  )
}

render (
  <App />,
  rootNode
)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"></script><div id="root"></div>

Upvotes: 27

Astra Bear
Astra Bear

Reputation: 2738

One of your problems is that FormData will only create entries for input fields that have BOTH: 1. A name and 2. A value.

It appears from your code that the you are missing the name. You should also capture the event like Yevhen shows: onSubmit

Doing both these things fixed the problem for me.

    <Form onSubmit={onFormSubmit}>
              <Form.Group className="mb-3" controlId="test1" >
                  <Form.Label>Some TextX</Form.Label>
                  <Form.Control type="text" placeholder="type something" name={"value1"} />
              </Form.Group>
             
              <Button variant="primary" type="submit">
                  Submit
              </Button>
</Form>

const onFormSubmit = (e:any) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        formData.append('title','John');
        let i=0;
        // @ts-ignore
        for (let [key, value] of formData.entries()) {
            console.log(i++,key, value);
        }
    };

Upvotes: 0

Related Questions