Hey again all, I have an easy question (i’m sure) for you. This is in ReactJS.
Whats going on… I have a form
-
onSubmit of the form I grab a dom div, and set innerHTML to a list of names (array).
-
I map through the array of names and for each iteration I grab a random color, and random greeting from two separate arrays in my component state and insert them into the mapped names. via dom.
Now all of this works well except, each time I submit my form, the previously saved random variables change as well as the current. See Images ->
class Content extends Component {
constructor(props) {
super(props);
this.state = {
names: "",
greetings: [
"Well well, look who finally shows up.",
"Boy am I glad to see you!",
"Enter the dojo my friend.",
"You arrived just in time!",
"Now that you're back, we can party!"
],
colors: ["#bb82f9", "#f4c3d5", "#fab916", "#61dafb", "#fc0d1c", "#84ffaf"]
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit = (e) => {
e.preventDefault();
const names = this.state.names.split(textAreaRegex);
const nametagsDiv = document.getElementById('nametags');
const greetings = this.state.greetings;
const colors = this.state.colors;
nametagsDiv.innerHTML = names.map(function(name, index) {
var randomGreeting = greetings[Math.floor(Math.random() * greetings.length)];
var randomColor = colors[Math.floor(Math.random() * colors.length)];
console.log(randomColor);
return `
<div key=${index} class="nametags-group flex">
<h1>${index + 1}.</h1>
<button type="button" class="nametag" style="background-color:${randomColor}">${name}</button>
<p class="greeting">${randomGreeting}</p>
</div>`
}).join('');
}