React - make input appear with text selectedLoop inside React JSXCan you force a React component to rerender without calling setState?Programmatically navigate using react routerWhy do we need middleware for async flow in Redux?React Hooks - What's happening under the hood?How do react hooks determine the component that they are for?How does useState() in react retrieve the correct state object and function for a functional component when using the state hook?React hooks function component prevent re-render on state updateReact Hooks, rerender & keeping same state - how it works underhood?React: Re-Rendering on Setting State - Hooks vs. this.setState

Running code generated in realtime in JavaScript with eval()

The oceans and the moon

Rebuses around the home

Heyawake: An Introductory Puzzle

Why do my bicycle brakes get worse and feel more 'squishy" over time?

Telephone number in spoken words

A+ rating still unsecure by Google Chrome's opinion

Are there really no countries that protect Freedom of Speech as the United States does?

Will using a resistor in series with a LED to control its voltage increase the total energy expenditure?

What's a good pattern to calculate a variable only when it is used the first time?

Graphs for which a calculus student can reasonably compute the arclength

What is a "soap"?

What if a restaurant suddenly cannot accept credit cards, and the customer has no cash?

When did Bilbo and Frodo learn that Gandalf was a Maia?

How can I shoot a bow using Strength instead of Dexterity?

Scam? Phone call from "Department of Social Security" asking me to call back

When was "Fredo" an insult to Italian-Americans?

Is there a word for returning to unpreparedness?

Is this bar slide trick shown on Cheers real or a visual effect?

Installing Windows to flash UEFI/ BIOS, then reinstalling Ubuntu

Is it OK to draw different current from L1 and L2 on NEMA 14-50?

List, map function based on a condition

Illustrator - SVG make thinner path

Is there a fallacy about "appeal to 'big words'"?



React - make input appear with text selected


Loop inside React JSXCan you force a React component to rerender without calling setState?Programmatically navigate using react routerWhy do we need middleware for async flow in Redux?React Hooks - What's happening under the hood?How do react hooks determine the component that they are for?How does useState() in react retrieve the correct state object and function for a functional component when using the state hook?React hooks function component prevent re-render on state updateReact Hooks, rerender & keeping same state - how it works underhood?React: Re-Rendering on Setting State - Hooks vs. this.setState






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








1















I have a functional component, that uses hooks.



const [editMode, setEditMode] = useState(false); 
...
return (
...
editMode && <input value="Some value">
}


When editMode is changed to true - the input field is appearing and I want it to appear with already selected text inside of it. How can I do this?




enter image description here










share|improve this question


























  • Have a look at useEffect and fire a function to select text

    – FrankerZ
    Mar 27 at 10:16











  • use local state for input value, it will work

    – Avinash Mahlawat
    Mar 27 at 10:17

















1















I have a functional component, that uses hooks.



const [editMode, setEditMode] = useState(false); 
...
return (
...
editMode && <input value="Some value">
}


When editMode is changed to true - the input field is appearing and I want it to appear with already selected text inside of it. How can I do this?




enter image description here










share|improve this question


























  • Have a look at useEffect and fire a function to select text

    – FrankerZ
    Mar 27 at 10:16











  • use local state for input value, it will work

    – Avinash Mahlawat
    Mar 27 at 10:17













1












1








1


1






I have a functional component, that uses hooks.



const [editMode, setEditMode] = useState(false); 
...
return (
...
editMode && <input value="Some value">
}


When editMode is changed to true - the input field is appearing and I want it to appear with already selected text inside of it. How can I do this?




enter image description here










share|improve this question
















I have a functional component, that uses hooks.



const [editMode, setEditMode] = useState(false); 
...
return (
...
editMode && <input value="Some value">
}


When editMode is changed to true - the input field is appearing and I want it to appear with already selected text inside of it. How can I do this?




enter image description here







reactjs react-hooks react-ref






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 10:18







Anna

















asked Mar 27 at 10:12









AnnaAnna

4505 silver badges19 bronze badges




4505 silver badges19 bronze badges















  • Have a look at useEffect and fire a function to select text

    – FrankerZ
    Mar 27 at 10:16











  • use local state for input value, it will work

    – Avinash Mahlawat
    Mar 27 at 10:17

















  • Have a look at useEffect and fire a function to select text

    – FrankerZ
    Mar 27 at 10:16











  • use local state for input value, it will work

    – Avinash Mahlawat
    Mar 27 at 10:17
















Have a look at useEffect and fire a function to select text

– FrankerZ
Mar 27 at 10:16





Have a look at useEffect and fire a function to select text

– FrankerZ
Mar 27 at 10:16













use local state for input value, it will work

– Avinash Mahlawat
Mar 27 at 10:17





use local state for input value, it will work

– Avinash Mahlawat
Mar 27 at 10:17












1 Answer
1






active

oldest

votes


















2














You can use the useRef hook to create a ref and put it on your input element, and use the useEffect hook to run a function every time editMode changes. If editMode is true, you can invoke the select method on the ref.current element.



Example






const useState, useRef, useEffect = React;

function App()
const [value, setValue] = useState("Some value");
const [editMode, setEditMode] = useState(false);
const ref = useRef();

useEffect(() =>
if (editMode)
ref.current.select();

, [editMode]);

return (
<div>
<button onClick=() => setEditMode(!editMode)>Toggle edit</button>
<div>
editMode && (
<input
ref=ref
value=value
onChange=e => setValue(e.target.value)
/>
)
</div>
</div>
);


ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>








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%2f55374672%2freact-make-input-appear-with-text-selected%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









    2














    You can use the useRef hook to create a ref and put it on your input element, and use the useEffect hook to run a function every time editMode changes. If editMode is true, you can invoke the select method on the ref.current element.



    Example






    const useState, useRef, useEffect = React;

    function App()
    const [value, setValue] = useState("Some value");
    const [editMode, setEditMode] = useState(false);
    const ref = useRef();

    useEffect(() =>
    if (editMode)
    ref.current.select();

    , [editMode]);

    return (
    <div>
    <button onClick=() => setEditMode(!editMode)>Toggle edit</button>
    <div>
    editMode && (
    <input
    ref=ref
    value=value
    onChange=e => setValue(e.target.value)
    />
    )
    </div>
    </div>
    );


    ReactDOM.render(<App />, document.getElementById("root"));

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <div id="root"></div>








    share|improve this answer































      2














      You can use the useRef hook to create a ref and put it on your input element, and use the useEffect hook to run a function every time editMode changes. If editMode is true, you can invoke the select method on the ref.current element.



      Example






      const useState, useRef, useEffect = React;

      function App()
      const [value, setValue] = useState("Some value");
      const [editMode, setEditMode] = useState(false);
      const ref = useRef();

      useEffect(() =>
      if (editMode)
      ref.current.select();

      , [editMode]);

      return (
      <div>
      <button onClick=() => setEditMode(!editMode)>Toggle edit</button>
      <div>
      editMode && (
      <input
      ref=ref
      value=value
      onChange=e => setValue(e.target.value)
      />
      )
      </div>
      </div>
      );


      ReactDOM.render(<App />, document.getElementById("root"));

      <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
      <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

      <div id="root"></div>








      share|improve this answer





























        2












        2








        2







        You can use the useRef hook to create a ref and put it on your input element, and use the useEffect hook to run a function every time editMode changes. If editMode is true, you can invoke the select method on the ref.current element.



        Example






        const useState, useRef, useEffect = React;

        function App()
        const [value, setValue] = useState("Some value");
        const [editMode, setEditMode] = useState(false);
        const ref = useRef();

        useEffect(() =>
        if (editMode)
        ref.current.select();

        , [editMode]);

        return (
        <div>
        <button onClick=() => setEditMode(!editMode)>Toggle edit</button>
        <div>
        editMode && (
        <input
        ref=ref
        value=value
        onChange=e => setValue(e.target.value)
        />
        )
        </div>
        </div>
        );


        ReactDOM.render(<App />, document.getElementById("root"));

        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

        <div id="root"></div>








        share|improve this answer















        You can use the useRef hook to create a ref and put it on your input element, and use the useEffect hook to run a function every time editMode changes. If editMode is true, you can invoke the select method on the ref.current element.



        Example






        const useState, useRef, useEffect = React;

        function App()
        const [value, setValue] = useState("Some value");
        const [editMode, setEditMode] = useState(false);
        const ref = useRef();

        useEffect(() =>
        if (editMode)
        ref.current.select();

        , [editMode]);

        return (
        <div>
        <button onClick=() => setEditMode(!editMode)>Toggle edit</button>
        <div>
        editMode && (
        <input
        ref=ref
        value=value
        onChange=e => setValue(e.target.value)
        />
        )
        </div>
        </div>
        );


        ReactDOM.render(<App />, document.getElementById("root"));

        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

        <div id="root"></div>








        const useState, useRef, useEffect = React;

        function App()
        const [value, setValue] = useState("Some value");
        const [editMode, setEditMode] = useState(false);
        const ref = useRef();

        useEffect(() =>
        if (editMode)
        ref.current.select();

        , [editMode]);

        return (
        <div>
        <button onClick=() => setEditMode(!editMode)>Toggle edit</button>
        <div>
        editMode && (
        <input
        ref=ref
        value=value
        onChange=e => setValue(e.target.value)
        />
        )
        </div>
        </div>
        );


        ReactDOM.render(<App />, document.getElementById("root"));

        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

        <div id="root"></div>





        const useState, useRef, useEffect = React;

        function App()
        const [value, setValue] = useState("Some value");
        const [editMode, setEditMode] = useState(false);
        const ref = useRef();

        useEffect(() =>
        if (editMode)
        ref.current.select();

        , [editMode]);

        return (
        <div>
        <button onClick=() => setEditMode(!editMode)>Toggle edit</button>
        <div>
        editMode && (
        <input
        ref=ref
        value=value
        onChange=e => setValue(e.target.value)
        />
        )
        </div>
        </div>
        );


        ReactDOM.render(<App />, document.getElementById("root"));

        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

        <div id="root"></div>






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 11:36

























        answered Mar 27 at 10:26









        TholleTholle

        51.4k8 gold badges66 silver badges89 bronze badges




        51.4k8 gold badges66 silver badges89 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%2f55374672%2freact-make-input-appear-with-text-selected%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