React change value inside the element

Viewed 118

I have a react element like this:

var element = 
<div> 
    <span>37</span> 
    <span>increased</span>
<div>

I want to modify this element by add "activities" after 37, so it becomes:

var element = 
<div> 
    <span>37 Activities</span> 
    <span>increased</span>
<div>

I am stucked on how to change this element. Is there a way to "inject" the string Activities to the element?

Note: I don't have access the the function which returns the element. What I can do is to modify the element.

Thanks

1 Answers

The explanation is a bit unclear. As far as I understand, you want to add the string Activities in the span tag after 37. I have added a way to achieve this using vanilla javascript. Get all the span tags on the page and do the manipulation.

Solution - online IDE

export default function App() {
  var element = (
   <div> 
    <span>37 </span> 
    <span>increased</span>
   </div>
  )
  const add = () => {
    document.getElementsByTagName('span')[0].innerHTML += 'Activities';
  }
 return (
   <div>
    {element}
    <button onClick={() => add()}> Add</button>
  </div>
 );
}

Hope this solution helps!

Related