-2

I am trying to set a timer to change the img src within reactbut it seems like this is not working.I saw that to write javascript we need to enclose it withing braces I did that but its still not helping. Code:-

class Default extends Component{
    render() {
    return (
       <div>              
          <Grid.Row style={{height: '250px',margin:'-10px'}} className="adbanner"> 
            <input id="ad" type="image" src={ad1} style={{position:'absolute',height:'50%',width:'100%'}}></input>
              {
                setTimeout(myFunction, 3000)
                myFunction{
                document.getElementById("ad").src="ad2";
                }
              }   

          </Grid.Row>
       </div>
    );
  }
}
export default Default;
J.Doe
  • 117
  • 1
  • 1
  • 9
  • Possible duplicate of [Creating custom function in React component](https://stackoverflow.com/questions/34875557/creating-custom-function-in-react-component) – Dexygen May 20 '18 at 04:52

1 Answers1

0

Wrapping within curly braces is when you're looking to render something on the screen. You're looking to perform an algorithmic operation, with no rendering involved. In this case, it doesn't belong in render

It looks like you're looking to run that function automatically when the component mounts. The react lifecycle event componentDidMount is the perfect run that operation. I took the liberty of fixing the syntax for myFunction and placing it outside of the component class.

function myFunction{
    document.getElementById("ad").src="ad2";
}

class Default extends Component{
    componentDidMount() {
        setTimeout(myFunction, 3000)
    }

    render() {
        return (
            <div>              
                <Grid.Row style={{height: '250px',margin:'-10px'}} className="adbanner"> 
                    <input id="ad" type="image" src={ad1} style={{position:'absolute',height:'50%',width:'100%'}}></input>
                </Grid.Row>
            </div>
        );
    }
}
export default Default;
Andrew
  • 7,201
  • 5
  • 25
  • 34