1

I want to declare a global variable inside of a function and then use it outside the function. I have tried putting the JSX inside of the function so I can easily access it but that doesn't work because the renderer returns null.

APP.JS:

class App extends React.Component {
  render() {
    firebase
      .database()
      .ref()
      .limitToLast(1)
      .on('child_added', function (childSnapshot) {
        var snap = childSnapshot.val();
        var category = snap.category;
        var condition = snap.condition;
        var postname = snap.postname;
        var postprice = snap.postprice;
        var username = snap.username;
        var usernumber = snap.usernumber;
        var imageURL = snap.imageURL;
        var postdescription = snap.postdescription;
        var whatsapplink = 'https://wa.me/' + usernumber + '?text=';
      });
    return (
      <>
        <div></div>
        <div style={{float: 'left'}}>
          <Ads
            imageURL={imageURL}
            name={postname}
            price={postprice}
            category={category}
            condition={condition}
            description={postdescription}
            username={username}
            usernumber={usernumber}
            whatsapplink={whatsapplink}
          />
        </div>
      </>
    );
  }
}

export default App;

Should I write a function to get data from firebase in the render?

ADS.JS:

import React from 'react';
import '../App.css';

class ads extends React.Component {
  render() {
    return (
      <div>
        <img src={this.props.image} alt="image"></img>
        <h2>{this.props.name}</h2>
        <h2>{this.props.price}</h2>
        <h2>{this.props.category}</h2>
        <h2>{this.props.condition}</h2>
        <h2>{this.props.description}</h2>
        <h2>{this.props.username}</h2>
        <a href={this.props.whatsapplink}>
          <button>Chat with Seller</button>
        </a>
      </div>
    );
  }
}

export default ads;
3
  • 1
    use state instead of global variables Commented Sep 30, 2020 at 12:20
  • 1
    I want to declare a global variable inside of a function and then use it outside the function. Hint: DON'T, this is not how react was meant to be used. What you want to do is to pass it as an argument to your components via props. Make sure you life state up to a common ancestor component. Commented Sep 30, 2020 at 12:20
  • Try to look into useContext hook. I'd suggest you passing a method to context that will be used to set that global value. Commented Sep 30, 2020 at 12:29

3 Answers 3

5

React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders. For more info about the lifecycle methods of React Go Through this doc

import React from 'react';
import firebase from 'firebase'
import './App.css'
import Ads from './component/ads.js'

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            category: '',
            condition: '',
            postname: '',
            postprice: '',
            username: '',
            usernumber: '',
            imageURL: '',
            postdescription: '',
            whatsapplink: ''
        }
    }
    componentDidMount() {
        firebase.database().ref().limitToLast(1).on('child_added', (childSnapshot) => {
            var snap = childSnapshot.val();
            this.setState({
                category: snap.category,
                condition: snap.condition,
                postname: snap.postname,
                postprice: snap.postprice,
                username: snap.username,
                usernumber: snap.usernumber,
                imageURL: snap.imageURL,
                postdescription: snap.postdescription,
                whatsapplink: "https://wa.me/" + snap.usernumber + "?text=",
            })
        })
    }
    render() {
        const { category, condition, postname, postprice, username, usernumber, imageURL, postdescription, whatsapplink } = this.state
        return (
            <>
                <div></div>
                <div style={{ float: "left" }}>
                    <Ads
                        category={category}
                        condition={condition}
                        name={postname}
                        price={postprice}
                        username={username}
                        usernumber={usernumber}
                        imageURL={imageURL}
                        description={postdescription}
                        whatsapplink={whatsapplink} />

                </div>
            </>
        )
    }
}

export default App;
Sign up to request clarification or add additional context in comments.

4 Comments

Good answer, but could you please add some more explanation to it instead of just "try this"
Its giving error : Cannot read property 'setState' of null
Your callback function is changing the context of this and its no longer the class. Either use an arrow function to get a lexical context: .on('value' , (x) => { .... Inside componentDidMount Firebase callback function
But Why though...?
3

If you really want a GLOBAL variable, you could use the window object and add a property to it. It's available everywhere I think.

Like this:

const myFunction = value => {
    window["newprop"] = value
}

But overall, it's not recommended

3 Comments

But overall, it's not recommended - then one would probably consider this not a helpful answer?
@Adam, if someone wants to know how to use a global variable, that's an answer. He didn't ask for best practices and neither did anyone else
@fesieg You haven't been on SO long enough to know - most people on SO ask questions like, "how do I do X" when what they really want to do Y. It's the answerer's job to tell the OP that they don't actually want to do X and instead they should be doing Y.
0

It's not a good idea to define a global variable in react js although the simplest way to define a global variable in React js is to put it on the window object. Inside your component you can define like

window.myGlobalVar = "I am a global var"; 

access it via

window.myGlobalVar

Ideally, if you want to pass data from component to component you can use

context

or can create higher order component

If your application is a complex one you can also use redux

2 Comments

Using state is enough, the change of props and state all cause rerenders but when you advise someone to put variables on the window it may cause bugs and it is an anti-pattern.
Why does everybody keep answering with, "this isn't a good idea, but here's how you do it"? You're going to hurt the OP more than help them with these answers.

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.