Search code examples
javascriptarraysreactjsreact-bootstrap

React - How do I display the first value of an array as the default value in a select form?


I am trying to display a property of the first object in an array as the default item. When I attempt to submit my form at the moment I get a null value for the selection because I have not engaged it. How would I make sure the value is present? I am using react-bootstrap. Below are the snippets of code representative of this issue:

Here is the focus, I'm not sure what to put in the value field. What I want is to reference the id value and if there is only one item in my array I don't have to open the dropdown, the id will already be there:

<Form.Control as="select" value={WHAT DO I DO HERE??} onChange={props.handleCart}>
   {props.carts.map((cart,i) => <option key={cart.id} value={cart.id}>{cart.cart_name</option>)})                 
</Form.Control>

Home.js

constructor() {
        super();
        this.state = {
    myCarts = [
    {'id':'1', 'cart_name': 'my cart 1'},
    {'id':'2', 'cart_name': 'my cart 2'}
    ],
showMenu: false
}
}

...

Return
<Create
showMenu = {this.state.showMenu}
menuModalToggle={this.menuModalToggle} 
carts = {this.state.carts}
/>

Create.js

const CreateMenuModal = (props) => {
    console.log('props carts there?',props.carts);
    return (
            <Modal
            //dialogClassName={classes.modal}
            show={props.showMenu}
            onHide={props.menuModalToggle}
            >
                 <Modal.Header closeButton>
                    <Modal.Title>Create Menu</Modal.Title>
                </Modal.Header>
                <div style={{ textAlign: 'center', padding: 10 }}>
                    Fill out the following details to create menus for your cart. Once you create a menu you will have the option to add and remove items from that menu.
                    </div>
                <Modal.Body>
                    <Form>
                        <Form.Group controlId="cart_check">
                            <Form.Label>Choose which cart this menu is for:</Form.Label>
                            <Form.Control as="select" value={WHAT DO I DO HERE??} onChange={props.handleCart}>
                            
                                   {props.carts.map((cart,i) => <option key={cart.id} value={cart.id}>{cart.cart_name}</option>)})
                    
                            </Form.Control>
                        </Form.Group>
                        <Form.Group controlId="menu_name">
                            <Form.Label>Enter a name for your menu:</Form.Label>
                            <Form.Control
                                required placeholder="My Menu" name="menu_name" type="email" onChange={props.handleChange} value={props.menu_name} 
                            />
                        </Form.Group>

                    </Form>
                </Modal.Body>
                <Modal.Footer>
                    <Button variant="secondary" onClick={props.menuModalToggle}>Cancel</Button>
                    <Button variant="primary" onClick={props.createMenu}>Add Menu</Button>
                </Modal.Footer>
        
            </Modal>

    )
}

Here is an example of the submit code for reference:

  //CREATE A MENU
        createMenu = () => {
            console.log('create menu with:', this.state.cart_id, this.state.menu_name);
            this.setState({ showMenu: !this.state.showMenu, menuAdded: !this.state.menuAdded });
            let sqlStamp = moment().utcOffset('-0400').format("YYYY-MM-DD HH:mm:ss").substr(0, 18) + '0';
            fetch(
                `${global.api}/addMenu?cart_id=${this.state.cart_id}&menu_name=${this.state.menu_name}&time_joined=${sqlStamp}`,
                { method: "POST" }
            ).catch((error) => {
                console.log(error)
            })
        }

Solution

  • Can you try defaultValue form-control-props

    <Form.Control
      as="select"
      value={props.carts[0].id.toString()}
      defaultValue={props.carts[0].id.toString()}
      onChange={props.handleCart}
    >
      {props.carts.map((cart,i) => (
        <option key={cart.id} value={cart.id}> 
           {cart.cart_name}
        </option>
      ))}
    </Form.Control>