Pass a text input from a function as a property so it can be exported as a const

I want to pass captured text from an input field as a property, so I can call it as a const in other components. How do I get the text to pass outside the function? The text is declared inside the function as the value.

import { useState } from 'react';

function Inputfield() {
    const [value, setValue] = useState("");

    return (
        <div>
            <input type="text" onChange={(e) => setValue(e.target.value)} />
            <br />
            <button
                onClick={
                    () => console.log(value)
                }>Get input value</button>
            {value}
        </div>
    );
}

export default Inputfield

Hello!

This is a case for a state manager like Redux.

The state of the input value(s) goes into a Redux store, where the values can also be updated. Other components can use the values. This way you can avoid chaotic imports and props drilling between components.

This a great opportunity to learn Redux:

There are more like Zustand:

to try out, but Redux is a good point to start.

Thanks I’ll have a look and give it a go!

You really do not need a state management library for this. You can pass values and functions down as props. Lift the state/state setters up in the component tree as needed (but not higher than needed).


You can also use the useReducer hook and Context. I would suggest you read the managing state section of the React docs before you start using a state management library.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.