HTML get the inner html tags value onSubmit of the form in React

Viewed 181

Hi I'm trying to get access to the value of the nested html tag 'option' on submit of the form, basically on submit of the form i should be able to access the value of option tag in the handleSubmit function. note: the code is in a React component, here is the html code:

 <div>
            <h1>Create notifications!</h1>
            <Form onSubmit={handleSubmit}>
                <Form.Group size="lg" controlId="email">
                    <Form.Label>choose your message</Form.Label>
                    <InputGroup.Text id="inputGroup-sizing-lg">Large</InputGroup.Text>
                    <Form.Select style={{ display: 'inline-block' }} size="lg" aria-label="Default select example">
                        <option>Click to choose message</option>
                        {mainNotifications.map((n, i) =>
                            <option key={i} name="selectMessage" /*this is what i want to get => */value={n.type}>{n.message}{n.type})</option>
                        )}
                    </Form.Select>
                </Form.Group>
                <Button className="button" block="true" size="lg" type="submit" >
                    Create Notification
                </Button>
            </Form>
            
        </div>)

and here are the libraries I'm using for it:

import React, { useEffect, useState } from 'react';
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import InputGroup from "react-bootstrap/InputGroup"
1 Answers

On top of your function (before return), add useState. For example:

const [selectboxValue, setSelectboxValue] = useState("");

Add onChange to your From.Select element:

<Form.Select onChange={e => setSelectboxValue(e.target.value)} style={{ display: 'inline-block' }} size="lg" aria-label="Default select example">

And then you can use selectboxValue inside your handleSubmit function.

Related