MinorityDev
MinorityDev

Reputation: 85

How do I call a function present in a javascript file once the React component is loaded?

What I am Attempting to do: Once the component is loaded I want to call getbg() from getMainBg.js to change the background.

My homepage component -

import React, { Component } from 'react';
import './Scripts/getMainBg.js';
class Homepage extends Component {
render() { 
return (

    <homepage>
        <div className="recent">
            <h1>Recently Added/Updated</h1>
                <div className="image">IMAGE1</div>
           </div>
           <div className="popular">
            <h1>Popular Right Now</h1>
                <div className="image"></div>
            </div>
        <div className="picks">
            <h1>Our Picks</h1>
                <div className="image"></div>
                <div className="image"></div>
        </div>
    </homepage>
    );
  }
}

export default Homepage;

My getMainBg.js -

var url = []; //will store image urls

function getbg(){
    var random = Math.floor(Math.random() * (url.length + 1)) + 0;
    document.getElementsByTagName("body")[0].style = "background-
    image: url('"+url[random]+"');";
    console.log('background loaded');
}

I tried to do but didn't work.

Upvotes: 0

Views: 46

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

You can use the componentDidMount function of a React component which is executed once when the React Component is mounted. Also you need to export the function before importing and calling it

import React, { Component } from 'react';
import { getbg } from './Scripts/getMainBg.js';

class Homepage extends Component {

    componentDidMount() {
       getbg();
    }
    render() { 
        return (

        <homepage>
            <div className="recent">
                <h1>Recently Added/Updated</h1>
                    <div className="image">IMAGE1</div>
               </div>
               <div className="popular">
                <h1>Popular Right Now</h1>
                    <div className="image"></div>
                </div>
            <div className="picks">
                <h1>Our Picks</h1>
                    <div className="image"></div>
                    <div className="image"></div>
            </div>
        </homepage>
        );
      }
}

getMainBg.js

var url = []; //will store image urls

export function getbg(){
    var random = Math.floor(Math.random() * (url.length + 1)) + 0;
    document.getElementsByTagName("body")[0].style = "background-
    image: url('"+url[random]+"');";
    console.log('background loaded');
}

Upvotes: 1

Related Questions