0
votes

I have an input field that requires a user to enter their name. I am using React useState hooks as follows (not full code, just example to give you an idea):

const inputBox = ( ) => {
const [inputText, setInputText] = useState("");

 const handleUserInput = (event) => {
    const newValue = event.target.value;
    setInputText(newValue);
  };

return (

<input onChange={handleUserInput} />

)};

How do I save and export only the updated value, i.e. the name the user typed.

Note I do not want to export the entire inputBox component, just the updated value so I can use it on another page without showing the physical input element on the new page. I do not want to display the username on another page, instead, I want to be able to import it as a string/variable and pass it to another function on the new page.

I have tried: I know how to display the user input on the same page as the physical input box because that can be done in the same inputBox component. The question is how to get just the value the user typed out of the component so I can export the inputText separately like: export default (inputBox) export { inputText };

Using props doesn't seem like a solution because I don't want to display the username or the input element elsewhere, I just want the value alone. I have also tried saving the value by setting a variable outside this component and then updating it when the user submits their name but it didn't quite work.

2
Thats not how you work in React, use Context API. Try reading the docs a bit - Dennis Vash

2 Answers

1
votes

You may create a context in the parent component and set a default value to it and update its value in your child component.

useState is to maintain the state of a component and it serves no other purpose. And it is not possible to export a state variable from a component.

You may refer Context API documentation here

0
votes

You can manage your state well with context or redux. Basically it allows you to have your state anywhere you like.

Here are the documentation of both approach:-

  1. Context API
  2. Redux

And here are some video guides you can follow:-

  1. React Context API
  2. React Redux