2

I want to made a hangman game in React.js and I have a function who take a random word among a list of word, I want to split this word and replace each letter by a "_ " but when I set the setState in the .map, it take only one "_" and not as many times as letters.

Someone can help me ?

const words = [...this.state.wordList];

const length = words.length;

const random = Math.floor(Math.random() * length);

const word = this.state.wordList[random].word;

const splitedWord = word.split("");

splitedWord.map(( letter, index ) => {
  const hiddenLetter = letter.replace(/./, "_");

  this.setState({usedWord: hiddenLetter});
}

4
  • 1
    It'd be better to provide a working example of the whole component. Also that part of code you've provided has syntax error. Commented Jun 14, 2018 at 11:59
  • Hard to tell without the rest of your code, but if you want to replace all letters by _, you need to add a global flag to the regex: letter.replace(/./g, "_"); (notice the g). But it makes little sense to call setState in a .map Commented Jun 14, 2018 at 12:00
  • 1
    Why even use map when all you need is _____? Just create that string. Something like const splittedWord = new Array(word.length + 1).join("_"); Then set the state to that. Commented Jun 14, 2018 at 12:00
  • 3
    In general it's not a good idea to setState() in every iteration of a loop. It's not efficient Commented Jun 14, 2018 at 12:01

1 Answer 1

1

The reason you are only getting one character replaced is because for each iteration you are replacing the original string, not the new one you generate in each loop. That being said, you shouldn't do it like that. As mentioned in the comments, using setState() in a loop is inefficient and unnecessary.


You already know that for the word Orange (6 letters) you want 6 _. As such, there is no need to iterate through each character and replace them one-by-one. Simply create a string of _ with said length!

You can do this with:

new Array(word.length + 1).join("_");

You are now ready to put this in your state. In other words:

this.setState({usedWord: new Array(word.length + 1).join("_")});
Sign up to request clarification or add additional context in comments.

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.