2

I'm trying to make simple animation text in React and JavaScript and my problem is that after mapping array with letters result in HTML what I get is <span>[Object object]</span>. Someone can explain what I do wrong.

animation = () => {
  let text = document.querySelector(".hi");
  let leterArr = [...text.textContent];
  text.textContent = "";
  leterArr.map(char => {
    return (text.innerHTML += "<span>" +{char} +"</span>")
  })
}
6
  • returning [object object] is not an issue .Beacuse you are returning an html tag.so Its shows like that only Commented Jul 5, 2020 at 14:33
  • 2
    You possibly meant to do leterArr.forEach(char => text.innerHTML += `<span>${char} </span>`) Commented Jul 5, 2020 at 14:34
  • possible duplicate of stackoverflow.com/questions/38548134/… Commented Jul 5, 2020 at 14:34
  • { char } creates an object literal using shorthand property names. Just remove the {} Commented Jul 5, 2020 at 14:35
  • 1
    or better: text.innerHTML = leterArr.map(char => `<span>${char}</span>`).join("") Commented Jul 5, 2020 at 14:35

2 Answers 2

2

React translate {char} to Object. So, when you concat it with string the object becomes [Object object]

use this

animation = () => {
  let text = document.querySelector(".hi");
  let leterArr = [...text.textContent];
  text.textContent = "";
  leterArr.map(char => {
    return (text.innerHTML += `<span>${char}</span>`)
  })
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to do something like this:

animation = () => {
  let text = document.querySelector(".hi");
  let leterArr = [...text.textContent];
  text.textContent = "";
  let temp;
  leterArr.map(char => {
    temp += "<span>" + char +"</span>"
  })
  text.innerHtml = temp;
}

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.