1

Use imported variable as a dinamic prop in React

Sorry for the noob question, but I'm a noob in React and I am strugling with this.

I have a file that exports a variable that is being mutated over time. Let's say something like this (not the real code, the variable is changing correctly):

// variable.js

let myVar = 0;


(setTimeout(function(){ myVar++ }, 3000))();

export { myVar };

and a react component that has to display the current value:

import React, { Component, Fragment } from "react";
import { myVar } from './variable.js';

export default class myComponent extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Fragment>
        <div>{myVar}</div>
      </Fragment>
    );
  }
}

What would be the best approach to get the variable displayed correctly while they change? I have tryied to set is as a state, as a prop and rendering it directly, but I am missing something.

I can not export a getter function, as I don't know from the component when the variable is going to change, but maybe I can change the approach? maybe throwing an event in each change?

Submitted December 29th 2020 by Admin

Answers
0

Try this, It won't work like the real-time update. But you can access like below

You can create a custom hook, that will update real-time

export default function useUpdate() { const [myVar, setState] = useState(0) setTimeout(function () { setState(myVar++); }, 3000); return [myVar, setState];
} import React, { Component, Fragment } from "react";
import { useUpdate } from './variable.js'; export default () => { const [myVar] = useUpdate(); return ( <Fragment> <div>{myVar}</div> </Fragment> );
}

Admin | 9 months ago


0

You can pass down the variable like a prop as below

<myComponent myVar={myVar} /> and then inside the component refer as props.myVar

The same thing can be achieved by a HOC as well if you prefer like this

const myNewComp = (myComponent)=>(props)=><myComponent myVar={myVar} {...props}/>

Admin | 9 months ago



Relevant Questions