Focus on TextField not working when button pressed in Dialog - Material UI












1















My goal is to set focus on a Material UI TextField after closing a Dialog by clicking a button in this Dialog.



The following piece of code works when I call it from a button that is not in a dialog component:



focusTitle = () => {
this.setState({ isOpen: false });
this.myRef.current.focus();
};


Code of button:



<Button onClick={this.focusTitle} />


Code of textfield I want to focus on:



<TextField
inputRef={this.myRef}
label="Title"
id="title"
multiline
rowsMax="4"
value={this.state.title}
autoFocus={true}
className={classes.title}
helperText="Enter a catchy title"
onChange={e => this.onTitleChange(e.target.value)}
/>


But as soon as I try to call the focusTitle() from a button within a dialog it does not trigger the focus.



Code of dialog:



<Dialog
open={this.state.isOpen}
onClose={this.focusTitle}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>

<DialogTitle id="alert-dialog-title">{"Warning"}</DialogTitle>

<DialogContent>
<DialogContentText id="alert-dialog-description">
Warning Message!
</DialogContentText>
</DialogContent>

<DialogActions>
<Button onClick={this.focusTitle} color="primary">
OK
</Button>
</DialogActions>
</Dialog>


Anyone has an idea why my .focus() is not working in the case of the dialog? If I log this.refs.myRef in both cases it shows the exact same result.



Thank you!










share|improve this question





























    1















    My goal is to set focus on a Material UI TextField after closing a Dialog by clicking a button in this Dialog.



    The following piece of code works when I call it from a button that is not in a dialog component:



    focusTitle = () => {
    this.setState({ isOpen: false });
    this.myRef.current.focus();
    };


    Code of button:



    <Button onClick={this.focusTitle} />


    Code of textfield I want to focus on:



    <TextField
    inputRef={this.myRef}
    label="Title"
    id="title"
    multiline
    rowsMax="4"
    value={this.state.title}
    autoFocus={true}
    className={classes.title}
    helperText="Enter a catchy title"
    onChange={e => this.onTitleChange(e.target.value)}
    />


    But as soon as I try to call the focusTitle() from a button within a dialog it does not trigger the focus.



    Code of dialog:



    <Dialog
    open={this.state.isOpen}
    onClose={this.focusTitle}
    aria-labelledby="alert-dialog-title"
    aria-describedby="alert-dialog-description"
    >

    <DialogTitle id="alert-dialog-title">{"Warning"}</DialogTitle>

    <DialogContent>
    <DialogContentText id="alert-dialog-description">
    Warning Message!
    </DialogContentText>
    </DialogContent>

    <DialogActions>
    <Button onClick={this.focusTitle} color="primary">
    OK
    </Button>
    </DialogActions>
    </Dialog>


    Anyone has an idea why my .focus() is not working in the case of the dialog? If I log this.refs.myRef in both cases it shows the exact same result.



    Thank you!










    share|improve this question



























      1












      1








      1








      My goal is to set focus on a Material UI TextField after closing a Dialog by clicking a button in this Dialog.



      The following piece of code works when I call it from a button that is not in a dialog component:



      focusTitle = () => {
      this.setState({ isOpen: false });
      this.myRef.current.focus();
      };


      Code of button:



      <Button onClick={this.focusTitle} />


      Code of textfield I want to focus on:



      <TextField
      inputRef={this.myRef}
      label="Title"
      id="title"
      multiline
      rowsMax="4"
      value={this.state.title}
      autoFocus={true}
      className={classes.title}
      helperText="Enter a catchy title"
      onChange={e => this.onTitleChange(e.target.value)}
      />


      But as soon as I try to call the focusTitle() from a button within a dialog it does not trigger the focus.



      Code of dialog:



      <Dialog
      open={this.state.isOpen}
      onClose={this.focusTitle}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
      >

      <DialogTitle id="alert-dialog-title">{"Warning"}</DialogTitle>

      <DialogContent>
      <DialogContentText id="alert-dialog-description">
      Warning Message!
      </DialogContentText>
      </DialogContent>

      <DialogActions>
      <Button onClick={this.focusTitle} color="primary">
      OK
      </Button>
      </DialogActions>
      </Dialog>


      Anyone has an idea why my .focus() is not working in the case of the dialog? If I log this.refs.myRef in both cases it shows the exact same result.



      Thank you!










      share|improve this question
















      My goal is to set focus on a Material UI TextField after closing a Dialog by clicking a button in this Dialog.



      The following piece of code works when I call it from a button that is not in a dialog component:



      focusTitle = () => {
      this.setState({ isOpen: false });
      this.myRef.current.focus();
      };


      Code of button:



      <Button onClick={this.focusTitle} />


      Code of textfield I want to focus on:



      <TextField
      inputRef={this.myRef}
      label="Title"
      id="title"
      multiline
      rowsMax="4"
      value={this.state.title}
      autoFocus={true}
      className={classes.title}
      helperText="Enter a catchy title"
      onChange={e => this.onTitleChange(e.target.value)}
      />


      But as soon as I try to call the focusTitle() from a button within a dialog it does not trigger the focus.



      Code of dialog:



      <Dialog
      open={this.state.isOpen}
      onClose={this.focusTitle}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
      >

      <DialogTitle id="alert-dialog-title">{"Warning"}</DialogTitle>

      <DialogContent>
      <DialogContentText id="alert-dialog-description">
      Warning Message!
      </DialogContentText>
      </DialogContent>

      <DialogActions>
      <Button onClick={this.focusTitle} color="primary">
      OK
      </Button>
      </DialogActions>
      </Dialog>


      Anyone has an idea why my .focus() is not working in the case of the dialog? If I log this.refs.myRef in both cases it shows the exact same result.



      Thank you!







      javascript reactjs material-ui






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 9:04







      Nicnel

















      asked Nov 20 '18 at 19:56









      NicnelNicnel

      185




      185
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Your dialog probably has a closing animation. As long as the animation is running, the focus() function will not be called correctly.



          To prevent this, create a callback for the animation or a timeout for the duration of the animation, to trigger the focus() afterwards. Like this:



          focusTitle = () => {
          this.setState({ isOpen: false });

          setTimeout(
          function() {
          this.myRef.current.focus();
          }
          .bind(this),
          500 // Change to duration of the animation
          };





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400609%2ffocus-on-textfield-not-working-when-button-pressed-in-dialog-material-ui%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Your dialog probably has a closing animation. As long as the animation is running, the focus() function will not be called correctly.



            To prevent this, create a callback for the animation or a timeout for the duration of the animation, to trigger the focus() afterwards. Like this:



            focusTitle = () => {
            this.setState({ isOpen: false });

            setTimeout(
            function() {
            this.myRef.current.focus();
            }
            .bind(this),
            500 // Change to duration of the animation
            };





            share|improve this answer




























              1














              Your dialog probably has a closing animation. As long as the animation is running, the focus() function will not be called correctly.



              To prevent this, create a callback for the animation or a timeout for the duration of the animation, to trigger the focus() afterwards. Like this:



              focusTitle = () => {
              this.setState({ isOpen: false });

              setTimeout(
              function() {
              this.myRef.current.focus();
              }
              .bind(this),
              500 // Change to duration of the animation
              };





              share|improve this answer


























                1












                1








                1







                Your dialog probably has a closing animation. As long as the animation is running, the focus() function will not be called correctly.



                To prevent this, create a callback for the animation or a timeout for the duration of the animation, to trigger the focus() afterwards. Like this:



                focusTitle = () => {
                this.setState({ isOpen: false });

                setTimeout(
                function() {
                this.myRef.current.focus();
                }
                .bind(this),
                500 // Change to duration of the animation
                };





                share|improve this answer













                Your dialog probably has a closing animation. As long as the animation is running, the focus() function will not be called correctly.



                To prevent this, create a callback for the animation or a timeout for the duration of the animation, to trigger the focus() afterwards. Like this:



                focusTitle = () => {
                this.setState({ isOpen: false });

                setTimeout(
                function() {
                this.myRef.current.focus();
                }
                .bind(this),
                500 // Change to duration of the animation
                };






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 9:34









                Thomas van BroekhovenThomas van Broekhoven

                494412




                494412
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400609%2ffocus-on-textfield-not-working-when-button-pressed-in-dialog-material-ui%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    'app-layout' is not a known element: how to share Component with different Modules

                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                    SQL update select statement