0

I want the string 'Surveillance Capitalism' to be inputted letter by letter into a text input (or something that looks like one) as a user types.

The code works up to the point I try to add the letter into the input, at which point I am told 'Failed prop type: You provided a value prop to a form field without an onChange handler'. Is this method possible? If not what is a good alternative?

Html:

<input
  id="search-bar"
  type="text"
  onKeyPress={this.handleKeyPress}
/>

JS:

//Dictates what is typed in the search bar
    (https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs)
  handleKeyPress = event => {
    var firstSearchString = "Surveillance Capitalism";
    //Converts firstSearchString into an array of its members (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
    var searchStringArray = Array.from(firstSearchString);
    //Gets contents of search bar
    var searchBar = document.getElementById("search-bar").value;
    //Length of that content
    var i = searchBar.length;
    searchBar.value += searchStringArray[i];
  };

Essentially I want to trick the user into thinking they can search whatever they want but when they go to type, my preset query will be entered letter by letter.

2 Answers 2

1

The problem is that you are assigning a variable to the search bar:

var searchBar = document.getElementById("search-bar").value;

then altering the variable, to fix your problem i just did this:

handleKeyPress = event => {
        var firstSearchString = "Surveillance Capitalism";
        var searchStringArray = Array.from(firstSearchString);
        for(let i = 0; i < searchStringArray.length; i++) {
            document.getElementById("search-bar").value += searchStringArray[i];
        }
  };

I think that's what you were having trouble with but i'm not sure if i understood the question. I hope this helped

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

1 Comment

Amazing! You fixed the error and then it only took a small tweak to get the desired effect, thanks!
0

Try the onChange event handler, rather than the onKeyPress handler. That should remove the error you have. They are functionally slightly different, but should accomplish the same thing.

Comments

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.