1

my code:

import "./styles.css";

export default function App() {

  getUserValue = (e) => {
    let value = e.target.value;
    console.log(value)
    return value
  }

  let userInputValue = getUserValue



 return (
    <div>
      <div>
        <h4>Sign Up</h4>
      </div>
          <div>
            <div>
                <p>Username</p>
                <input  onChange = {getUserValue}/> 
            </div>
            <div >
                <p>Password</p>
                <input/> 
            </div>
          </div>
          <div> 
            <button onClick = {console.log(userInputValue)}>Submit</button>
          </div>
      <div>
        <button>
          Close
        </button>
      </div>
  </div>
  );
}

code sandbox: https://codesandbox.io/s/dazzling-sea-my5qm?file=/src/App.js:0-720

I'm trying to store the returned value of "getUserValue" function to "userInputValue" variable so I can log the input the user made and use it in different functions. I can't get it to work though, when I console log the variable hoping to get the returned result after I made an input I don't get anything, as if the button doesn't work.

4
  • "code sandbox" Please put your runnable examples here, on-site, not just offsite. Four reasons: It's really easy to forget to include everything if you rely on off-site resources; people shouldn't have to go off-site to help you; some sites are blocked for some users; and links rot, making the question and its answers useless to people in the future. Please put a minimal reproducible example in the question. More: How do I ask a good question? and Something in my web site or project doesn't work. Can I just paste a link to it? Commented May 8, 2021 at 12:52
  • You can do that using Stack Snippets (the [<>] toolbar button). Stack Snippets support React, including JSX; here's how to do one. Commented May 8, 2021 at 12:52
  • Side note: Handling the change event on the div rather than the input is fairly unusual... Commented May 8, 2021 at 12:55
  • 1
    I was trying to recreate my example from my files, and I understand your point for not linking to it offsite. That is why I made sure to include the example on-site in my question and off-site as well. I laughed a bit when you helped me notice I included the onChange event in my div :D excuse me I might have rushed a few things when I made my example. I fixed my example accordingly. Hope I get an answer soon. Commented May 8, 2021 at 13:03

1 Answer 1

1

I'm trying to store the returned value of "getUserValue" function to "userInputValue" variable so I can log the input the user made and use it in different functions.

You'd do that by making the input state in your component. In a function component like yours, that means using the useState hook (or various libraries like Redux that have alternative ways of doing it).

Here's a simple example, but you can find lots of more complex ones by searching:

const { useState } = React;

function Example() {
    // Call the hook to get the current value and to
    // get a setter function to change it. The default
    // value ("" in this example) is only used the first
    // time you call the hook in this component's lifecycle
    const [userInput, setUserInput] = useState("");
    
    // Handle changes in the input by setting state.
    // Note that this function is recreated every time your
    // component function is called to update. That's mostly
    // fine, but there are times you might want to optimize
    // that.
    const onChange = (event) => {
        setUserInput(event.currentTarget.value);
    };
    
    // Handle clicks on the button that show' the current input.
    const onClick = () => {
        console.log(`The current userInput is "${userInput}"`);
    };
    
    // Return the rendering information for React
    return <div>
        {/* Provide the value and hook the "change" (really "input") event */}
        <input type="text" value={userInput} onChange={onChange} />
        <input type="button" onClick={onClick} value="Show Current" />
    </div>;
}

ReactDOM.render(<Example />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

I have experience using react class state and redux and now I realize that I could've also done that example using those tools. I was using redux in my project and was trying to take the input value from the input field and when the user clicks the submit button, trigger a dispatch that sends the payload to the reducer and returns the new state of both the username and password field. Would using state hooks be the answer to this problem?
@momomo - There's also a standard useReducer hook which is slightly/minimally Redux-like. Or Redux has several hooks: useDispatch, useStore, useSelector...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.