P
P
petro5052020-04-27 15:51:12
JavaScript
petro505, 2020-04-27 15:51:12

How to write in state what the user entered into the input after pressing the button?

There is a task: when the user enters some word into the input and presses the Search button , this word should be set as the value in the field inputValue. But I have no experience with inputs and buttons that send somewhere the value that the user entered.

app.js file:

import Search from ./Search.js
const App = () => {

  const [value, setValue] = useState({
    data: [],
    inputValue: ""
  });

/* Здесь должен быть какой-то такой метод который срабатывает когда считано значение с инпута и нажата кнопка

const какой-то метод = () => {    
      setValue((prev) => ({
       ...prev,
       inputValue:  устанвливаю значением то что ввел пользователь в инпут
     }));
    }; 
*/

/* И возможно нужно еще какой-то такой метод, но не уверен что его нужно. Я чесно плохо понимаю как считывать данные с инпутов. Но в одном коде видел что-то такое. 
    
const updateSearchInput = (e) => {
       setValue((prev) => ({
         searchInput: e.target.value
       }));
     };

*/

return (
    <div>
      <Search     здесь передают атрибуты какие-то />  
      <Table data={value.data}/>
   </div>
  );
};


And there is an input with a button (Search.js file)
export default () => {
  return (
    <div>
        <input type="text" />
        <button>Search</button>
    </div>
  );
};


It looks like this:

5ea6d053576f9594246844.png

What do I need to add to the code of the App.js file and the Search.js file in order to implement the task?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-04-27
@petro505

Let Search store the value that the user enters and accept a button click handler that will be passed the value when called:

const Search = props => {
  const [ value, setValue ] = React.useState('');

  return (
    <div>
      <input type="text" value={value} onChange={e => setValue(e.target.value)} />
      <button onClick={() => props.onSearch(value)}>Search</button>
    </div>
  );
};

And in the parent component, respectively, in Search, you pass a function that will update what you need there:
<Search onSearch={search => setValue({ ...value, inputValue: search })} />

UPD. https://jsfiddle.net/fp0dvhrg/

S
shsv382, 2020-04-27
@shsv382

App.js should be a stateful component. Just track the onchange on the input:

onChange(e) {
    this.setState({inputValue: e.target.value})
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question