Skip to content
Advertisement

React JS changing words in spherical word cloud

https://codesandbox.io/s/basic-demo-forked-yup2o?file=/src/App.js

I have the above sandbox of a spherical word cloud consisting of random words – I’m trying to modify the code so rather than random words, the cloud can display words from a list of my choosing, for example

let MyList = ['React', 'Node', 'SQL', 'NoSQL', 'TDD', 'JavaScript', 'Python', 'Git', 'Excel', 'ReactNative', 'HTML', 'CSS', 'TypeScript', 'Java', 'Angular', 'Django']

I tried doing this by editing the code inside the for loop of the cloud function by changing randomWord() to wordFromMyList() which is defined below.

function wordFromMyList() { 
    let y = MyList[0];
    MyList.shift();
    return y 
}

However this isn’t working and doesn’t return a spherical cloud at all – but if I instead change the wordFromMyList() function to just return ‘hi’ I get a spherical word cloud with only the word ‘hi’ which is confusing me as to why the shift function doesn’t seem to be working.

Any suggestions?

Advertisement

Answer

It is due to too many re-renders (4 to be exact) and by then your MyList is already shifted more than 16 times and is empty. So your function wordFromMyList is always returning undefined by the 4rth render and nothing is getting displayed.

Use i and j variables in the two loops to get the word from your list like this

  function wordFromMyList(i, j) {
    return MyList[i * 4 + j];
  }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement