How to use refs to shift focus to an P element?React – the right way to pass form element state to sibling/parent elements?Show or hide element in ReactInvariant Violation: _registerComponent(…): Target container is not a DOM elementSet focus on input after renderUse state or refs in React.js form components?Parse Error: Adjacent JSX elements must be wrapped in an enclosing tagHow to pass props to this.props.childrenUncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: objectCannot update during an existing state transitionUse ref to focus but set ref with conditioning

How to query data in backups?

Blocking people from taking pictures of me with smartphone

Team goes to lunch frequently, I do intermittent fasting but still want to socialize

Is this cheap "air conditioner" able to cool a room?

Is it double speak?

English - Acceptable use of parentheses in an author's name

Traveling from Germany to other countries by train?

Should I self-publish my novella on Amazon or try my luck getting publishers?

Why did the RAAF procure the F/A-18 despite being purpose-built for carriers?

Infeasibility in mathematical optimization models

How to display a duet in lyrics?

Why are the inside diameters of some pipe larger than the stated size?

Why is there a need to prevent a racist, sexist, or otherwise bigoted vendor from discriminating who they sell to?

Are there any financial disadvantages to living significantly "below your means"?

What are good ways to improve as a writer other than writing courses?

How do I change the output voltage of the LM7805?

What word can be used to describe a bug in a movie?

Ex-contractor published company source code and secrets online

Why was CPU32 core created, and how is it different from 680x0 CPU cores?

What happen if I gain the control of aura that enchants an opponent's creature? Would the aura stay attached?

Non-OR journals which regularly publish OR research

Where to pee in London?

Is it true that control+alt+delete only became a thing because IBM would not build Bill Gates a computer with a task manager button?

Does this smartphone photo show Mars just below the Sun?



How to use refs to shift focus to an P element?


React – the right way to pass form element state to sibling/parent elements?Show or hide element in ReactInvariant Violation: _registerComponent(…): Target container is not a DOM elementSet focus on input after renderUse state or refs in React.js form components?Parse Error: Adjacent JSX elements must be wrapped in an enclosing tagHow to pass props to this.props.childrenUncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: objectCannot update during an existing state transitionUse ref to focus but set ref with conditioning






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have a timeline component when you click on a month that shifts focus to reports of that month



I have used refs to try and achieve this. I update the state on click of an element on the timeline so I use the focus function in componentDidUpdate method



data.map(factsheet => 
const heading = factsheet && toShortFormat(factsheet.month).slice(3);
return (
<Cell extraClasses="factsheets-container">
<p className="month-name" ref=heading>heading</p>
<Cell extraClasses="factsheets">
this.factsheetsList(factsheet.factsheets)
</Cell>
</Cell>
)
);


This snippet is for refs in onclick function



const ref = `$month-$year`;
this.setState(
ref: this.refs[ref],
)


This is the componentDidUpdate function



componentDidUpdate () 
const ref = this.state
ref && ReactDOM.findDOMNode(ref).focus();



The focus doesn't shift










share|improve this question
































    1















    I have a timeline component when you click on a month that shifts focus to reports of that month



    I have used refs to try and achieve this. I update the state on click of an element on the timeline so I use the focus function in componentDidUpdate method



    data.map(factsheet => 
    const heading = factsheet && toShortFormat(factsheet.month).slice(3);
    return (
    <Cell extraClasses="factsheets-container">
    <p className="month-name" ref=heading>heading</p>
    <Cell extraClasses="factsheets">
    this.factsheetsList(factsheet.factsheets)
    </Cell>
    </Cell>
    )
    );


    This snippet is for refs in onclick function



    const ref = `$month-$year`;
    this.setState(
    ref: this.refs[ref],
    )


    This is the componentDidUpdate function



    componentDidUpdate () 
    const ref = this.state
    ref && ReactDOM.findDOMNode(ref).focus();



    The focus doesn't shift










    share|improve this question




























      1












      1








      1








      I have a timeline component when you click on a month that shifts focus to reports of that month



      I have used refs to try and achieve this. I update the state on click of an element on the timeline so I use the focus function in componentDidUpdate method



      data.map(factsheet => 
      const heading = factsheet && toShortFormat(factsheet.month).slice(3);
      return (
      <Cell extraClasses="factsheets-container">
      <p className="month-name" ref=heading>heading</p>
      <Cell extraClasses="factsheets">
      this.factsheetsList(factsheet.factsheets)
      </Cell>
      </Cell>
      )
      );


      This snippet is for refs in onclick function



      const ref = `$month-$year`;
      this.setState(
      ref: this.refs[ref],
      )


      This is the componentDidUpdate function



      componentDidUpdate () 
      const ref = this.state
      ref && ReactDOM.findDOMNode(ref).focus();



      The focus doesn't shift










      share|improve this question
















      I have a timeline component when you click on a month that shifts focus to reports of that month



      I have used refs to try and achieve this. I update the state on click of an element on the timeline so I use the focus function in componentDidUpdate method



      data.map(factsheet => 
      const heading = factsheet && toShortFormat(factsheet.month).slice(3);
      return (
      <Cell extraClasses="factsheets-container">
      <p className="month-name" ref=heading>heading</p>
      <Cell extraClasses="factsheets">
      this.factsheetsList(factsheet.factsheets)
      </Cell>
      </Cell>
      )
      );


      This snippet is for refs in onclick function



      const ref = `$month-$year`;
      this.setState(
      ref: this.refs[ref],
      )


      This is the componentDidUpdate function



      componentDidUpdate () 
      const ref = this.state
      ref && ReactDOM.findDOMNode(ref).focus();



      The focus doesn't shift







      reactjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 7:01







      Shubham Bhardwaj

















      asked Mar 27 at 6:54









      Shubham BhardwajShubham Bhardwaj

      659 bronze badges




      659 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          0














          I'm not sure how you are using the ref because we can't see your whole Component, but, from what I see, there is something wrong (for example, you should have one refObject for each Cell, and you should not save the refs in the state).

          I can't even see where the onClick function is fired :)



          Anyways, here's a fiddle that may help you:






          const data = [
          title: "Foo",
          title: "Bar",
          title: "Miz"
          ];

          class App extends React.Component
          inputListRef;

          constructor(props)
          super(props);

          this.inputListRef = Array.from( length: props.data.length, () => React.createRef());


          handleClick = (e) =>
          const dataIndex = e.target.getAttribute("data-index");
          this.inputListRef[dataIndex].current.focus()
          console.log();


          render()
          return (
          <React.Fragment>
          <h1>Your Data</h1>
          this.props.data.map((el, index) =>
          return (
          <div className="data-cell">
          <button data-index=index onClick=this.handleClick>Click me for Focus</button>
          <input type="text" ref=this.inputListRef[index] value=el.title></input>
          </div>
          );
          )
          </React.Fragment>
          );



          ReactDOM.render(<App data=data/>, document.getElementById('root'));

          @import url(https://fonts.googleapis.com/css?family=Montserrat);

          body
          font-family: 'Montserrat', sans-serif;


          .data-cell
          border: 1px solid rgba(0,0,0,0.5);
          display: block;
          width: 300px;
          padding: 10px;


          .data-cell + .data-cell
          margin-top: 20px;

          <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

          <div id='root'></div>





          I've used the input element so you can see the focus easily. As you can see, I create an array of refs, and I save each input element in one different entry of the array.



          Notice I've used the data-index custom attribute: you could also write onClick=() => this.handleClick(index) and change the handleClick() to expect a number parameter; I wrote like I wrote because I wanted to avoid arrow function in render() method.



          Does it help you?






          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%2f55371382%2fhow-to-use-refs-to-shift-focus-to-an-p-element%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









            0














            I'm not sure how you are using the ref because we can't see your whole Component, but, from what I see, there is something wrong (for example, you should have one refObject for each Cell, and you should not save the refs in the state).

            I can't even see where the onClick function is fired :)



            Anyways, here's a fiddle that may help you:






            const data = [
            title: "Foo",
            title: "Bar",
            title: "Miz"
            ];

            class App extends React.Component
            inputListRef;

            constructor(props)
            super(props);

            this.inputListRef = Array.from( length: props.data.length, () => React.createRef());


            handleClick = (e) =>
            const dataIndex = e.target.getAttribute("data-index");
            this.inputListRef[dataIndex].current.focus()
            console.log();


            render()
            return (
            <React.Fragment>
            <h1>Your Data</h1>
            this.props.data.map((el, index) =>
            return (
            <div className="data-cell">
            <button data-index=index onClick=this.handleClick>Click me for Focus</button>
            <input type="text" ref=this.inputListRef[index] value=el.title></input>
            </div>
            );
            )
            </React.Fragment>
            );



            ReactDOM.render(<App data=data/>, document.getElementById('root'));

            @import url(https://fonts.googleapis.com/css?family=Montserrat);

            body
            font-family: 'Montserrat', sans-serif;


            .data-cell
            border: 1px solid rgba(0,0,0,0.5);
            display: block;
            width: 300px;
            padding: 10px;


            .data-cell + .data-cell
            margin-top: 20px;

            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

            <div id='root'></div>





            I've used the input element so you can see the focus easily. As you can see, I create an array of refs, and I save each input element in one different entry of the array.



            Notice I've used the data-index custom attribute: you could also write onClick=() => this.handleClick(index) and change the handleClick() to expect a number parameter; I wrote like I wrote because I wanted to avoid arrow function in render() method.



            Does it help you?






            share|improve this answer





























              0














              I'm not sure how you are using the ref because we can't see your whole Component, but, from what I see, there is something wrong (for example, you should have one refObject for each Cell, and you should not save the refs in the state).

              I can't even see where the onClick function is fired :)



              Anyways, here's a fiddle that may help you:






              const data = [
              title: "Foo",
              title: "Bar",
              title: "Miz"
              ];

              class App extends React.Component
              inputListRef;

              constructor(props)
              super(props);

              this.inputListRef = Array.from( length: props.data.length, () => React.createRef());


              handleClick = (e) =>
              const dataIndex = e.target.getAttribute("data-index");
              this.inputListRef[dataIndex].current.focus()
              console.log();


              render()
              return (
              <React.Fragment>
              <h1>Your Data</h1>
              this.props.data.map((el, index) =>
              return (
              <div className="data-cell">
              <button data-index=index onClick=this.handleClick>Click me for Focus</button>
              <input type="text" ref=this.inputListRef[index] value=el.title></input>
              </div>
              );
              )
              </React.Fragment>
              );



              ReactDOM.render(<App data=data/>, document.getElementById('root'));

              @import url(https://fonts.googleapis.com/css?family=Montserrat);

              body
              font-family: 'Montserrat', sans-serif;


              .data-cell
              border: 1px solid rgba(0,0,0,0.5);
              display: block;
              width: 300px;
              padding: 10px;


              .data-cell + .data-cell
              margin-top: 20px;

              <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
              <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

              <div id='root'></div>





              I've used the input element so you can see the focus easily. As you can see, I create an array of refs, and I save each input element in one different entry of the array.



              Notice I've used the data-index custom attribute: you could also write onClick=() => this.handleClick(index) and change the handleClick() to expect a number parameter; I wrote like I wrote because I wanted to avoid arrow function in render() method.



              Does it help you?






              share|improve this answer



























                0












                0








                0







                I'm not sure how you are using the ref because we can't see your whole Component, but, from what I see, there is something wrong (for example, you should have one refObject for each Cell, and you should not save the refs in the state).

                I can't even see where the onClick function is fired :)



                Anyways, here's a fiddle that may help you:






                const data = [
                title: "Foo",
                title: "Bar",
                title: "Miz"
                ];

                class App extends React.Component
                inputListRef;

                constructor(props)
                super(props);

                this.inputListRef = Array.from( length: props.data.length, () => React.createRef());


                handleClick = (e) =>
                const dataIndex = e.target.getAttribute("data-index");
                this.inputListRef[dataIndex].current.focus()
                console.log();


                render()
                return (
                <React.Fragment>
                <h1>Your Data</h1>
                this.props.data.map((el, index) =>
                return (
                <div className="data-cell">
                <button data-index=index onClick=this.handleClick>Click me for Focus</button>
                <input type="text" ref=this.inputListRef[index] value=el.title></input>
                </div>
                );
                )
                </React.Fragment>
                );



                ReactDOM.render(<App data=data/>, document.getElementById('root'));

                @import url(https://fonts.googleapis.com/css?family=Montserrat);

                body
                font-family: 'Montserrat', sans-serif;


                .data-cell
                border: 1px solid rgba(0,0,0,0.5);
                display: block;
                width: 300px;
                padding: 10px;


                .data-cell + .data-cell
                margin-top: 20px;

                <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

                <div id='root'></div>





                I've used the input element so you can see the focus easily. As you can see, I create an array of refs, and I save each input element in one different entry of the array.



                Notice I've used the data-index custom attribute: you could also write onClick=() => this.handleClick(index) and change the handleClick() to expect a number parameter; I wrote like I wrote because I wanted to avoid arrow function in render() method.



                Does it help you?






                share|improve this answer













                I'm not sure how you are using the ref because we can't see your whole Component, but, from what I see, there is something wrong (for example, you should have one refObject for each Cell, and you should not save the refs in the state).

                I can't even see where the onClick function is fired :)



                Anyways, here's a fiddle that may help you:






                const data = [
                title: "Foo",
                title: "Bar",
                title: "Miz"
                ];

                class App extends React.Component
                inputListRef;

                constructor(props)
                super(props);

                this.inputListRef = Array.from( length: props.data.length, () => React.createRef());


                handleClick = (e) =>
                const dataIndex = e.target.getAttribute("data-index");
                this.inputListRef[dataIndex].current.focus()
                console.log();


                render()
                return (
                <React.Fragment>
                <h1>Your Data</h1>
                this.props.data.map((el, index) =>
                return (
                <div className="data-cell">
                <button data-index=index onClick=this.handleClick>Click me for Focus</button>
                <input type="text" ref=this.inputListRef[index] value=el.title></input>
                </div>
                );
                )
                </React.Fragment>
                );



                ReactDOM.render(<App data=data/>, document.getElementById('root'));

                @import url(https://fonts.googleapis.com/css?family=Montserrat);

                body
                font-family: 'Montserrat', sans-serif;


                .data-cell
                border: 1px solid rgba(0,0,0,0.5);
                display: block;
                width: 300px;
                padding: 10px;


                .data-cell + .data-cell
                margin-top: 20px;

                <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

                <div id='root'></div>





                I've used the input element so you can see the focus easily. As you can see, I create an array of refs, and I save each input element in one different entry of the array.



                Notice I've used the data-index custom attribute: you could also write onClick=() => this.handleClick(index) and change the handleClick() to expect a number parameter; I wrote like I wrote because I wanted to avoid arrow function in render() method.



                Does it help you?






                const data = [
                title: "Foo",
                title: "Bar",
                title: "Miz"
                ];

                class App extends React.Component
                inputListRef;

                constructor(props)
                super(props);

                this.inputListRef = Array.from( length: props.data.length, () => React.createRef());


                handleClick = (e) =>
                const dataIndex = e.target.getAttribute("data-index");
                this.inputListRef[dataIndex].current.focus()
                console.log();


                render()
                return (
                <React.Fragment>
                <h1>Your Data</h1>
                this.props.data.map((el, index) =>
                return (
                <div className="data-cell">
                <button data-index=index onClick=this.handleClick>Click me for Focus</button>
                <input type="text" ref=this.inputListRef[index] value=el.title></input>
                </div>
                );
                )
                </React.Fragment>
                );



                ReactDOM.render(<App data=data/>, document.getElementById('root'));

                @import url(https://fonts.googleapis.com/css?family=Montserrat);

                body
                font-family: 'Montserrat', sans-serif;


                .data-cell
                border: 1px solid rgba(0,0,0,0.5);
                display: block;
                width: 300px;
                padding: 10px;


                .data-cell + .data-cell
                margin-top: 20px;

                <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

                <div id='root'></div>





                const data = [
                title: "Foo",
                title: "Bar",
                title: "Miz"
                ];

                class App extends React.Component
                inputListRef;

                constructor(props)
                super(props);

                this.inputListRef = Array.from( length: props.data.length, () => React.createRef());


                handleClick = (e) =>
                const dataIndex = e.target.getAttribute("data-index");
                this.inputListRef[dataIndex].current.focus()
                console.log();


                render()
                return (
                <React.Fragment>
                <h1>Your Data</h1>
                this.props.data.map((el, index) =>
                return (
                <div className="data-cell">
                <button data-index=index onClick=this.handleClick>Click me for Focus</button>
                <input type="text" ref=this.inputListRef[index] value=el.title></input>
                </div>
                );
                )
                </React.Fragment>
                );



                ReactDOM.render(<App data=data/>, document.getElementById('root'));

                @import url(https://fonts.googleapis.com/css?family=Montserrat);

                body
                font-family: 'Montserrat', sans-serif;


                .data-cell
                border: 1px solid rgba(0,0,0,0.5);
                display: block;
                width: 300px;
                padding: 10px;


                .data-cell + .data-cell
                margin-top: 20px;

                <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

                <div id='root'></div>






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 8:13









                JollyJolly

                6717 silver badges17 bronze badges




                6717 silver badges17 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    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%2f55371382%2fhow-to-use-refs-to-shift-focus-to-an-p-element%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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript