0

I want to create a method taking an array as parameter, that renders two divs, one displaying the text of the object in the array, second allows user to go to the next text in the array.

However, even though the variable is being incremented the div doesn't re-render with new text. How I can do this without creating a lot of code like redux?

Code below:

const array = [{text: '1st text'}, {text: "2nd text"}]
dialogueReceiver = (array, i) =>{
        let i = 0;
        const increment = () =>{
            i++;
        }
        return(
            <div>

                <div> {array[i].text} </div>
                <div onClick={ () => increment()}> NEXT </div>
            </div>
        )
    }
Red
  • 6,599
  • 9
  • 43
  • 85
MazMat
  • 1,904
  • 3
  • 12
  • 24
  • https://stackoverflow.com/questions/46240647/can-i-call-forceupdate-in-stateless-component – TKoL May 08 '18 at 11:48
  • The react way you'll need to update the component via props / setState, just plain javascript you need a to write a simple pub sub method, or write direct to the dom with an eventlistener. But if you are using react you should do things the react way. – digital-pollution May 08 '18 at 11:53
  • Got it, creating a state for it then, thought I could avoid it for such little thing in this component – MazMat May 08 '18 at 11:56
  • not the best option, but you could have a look at forceUpdate(): https://reactjs.org/docs/react-component.html#forceupdate – gianni May 08 '18 at 14:39
  • Perhaps adding `key` attribute to parent `div` do the trick. Change that to `
    ...rest of the code`
    – StackedQ May 09 '18 at 11:22

0 Answers0