Search code examples
javascriptjqueryreactjsreact-bootstrapreact-bootstrap-form

Form control react bootstrap textarea editable on open


Currently, I'm using the following field to get input from the user details_field

    <Form.Label>Details</Form.Label>
    <Form.Control
      type="text"
      readOnly
      value={
        responseObject[item.user_response_details.id]
          ? responseObject[item.user_response_details.id].comments
          : item.user_response_details.comments
      }
      onClick={(e) => {
        setModalShow(true);      // Sets the visibility of the modal                        
      }}
      onFocusCapture={() => {
        setPrevState(responseObject);
      }}
      onChange={(e) => {
        setComments(e.target.value);
      }}
      onBlur={() => {
        console.log(newComment);
        if (comments && comments !== '' && newComment) {
          dispatch(IncrementCompletedActivityCount({ count: 1 }));
          setNew(false);
        }
      }}
      required
    />
    <Form.Text>
    </Form.Text>

On clicking on the field the modal is shown but to enter text in details popup I have to provide an extra click to start editing the details details_box_popup

{modalShow && (
  <DetailsModal
    id={activityId}
    item={currentItem}
    loginUserGroups={loginUserGroups}
    onHide={() => setModalShow(false)}
  />
)}

Can this be implemented without the extra click that need to be provided while adding details in the


Solution

  • While displaying the modal DetailsModal local reference can be created using useRef hook as follows:

    DetailsModal(props) {
      const elementRef = useRef();
      useEffect(() => {
    
        elementRef.current.focus();
      }, []);
    
    <Form.Group className="mb-0" controlId="exampleForm.ControlTextarea1">
                  <Form.Control
                    as="textarea"
                    onChange={(e) => {
    
                      setComments(e.target.value);
                    }}
                    rows={7}
                    ref={elementRef} // using the reference created
                  />
                </Form.Group>
    

    This will bring in the focus on the field without onClick