-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;
1

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

but I am getting this error:- Unexpected token, expected at function myFunction{
is it occuring becoz the function is defined outside the class?

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.