How can i use static variable with React Hooks
?
I have a component and I want to pass it to hooks, but I have a problem because of static
Old Exemplo:
class MyComponent extends Component {
static myComponentInstance
static show({...config}){
this.myComponentInstance.start(config)
}
start({...config}){ // my code function here }
}
new Version
const MyComponent = (props) => {
const myComponentInstance = useRef(null)
const start = ({...config}){ // my code function here }
}
I saw a bit of useRef
, but I don't know if it's right to use it, and how I would make my show method static
doing this, I can call my component's method from another component (it already works with the class)
Ex:
import { Root, myComponent } from 'myComponent'
<Root>
<a onclick="myComponent.show({...})">Show</a>
</Root>
Is it possible to use static methods
with react hooks
?
How can i use static variable with React Hooks
?
I have a component and I want to pass it to hooks, but I have a problem because of static
Old Exemplo:
class MyComponent extends Component {
static myComponentInstance
static show({...config}){
this.myComponentInstance.start(config)
}
start({...config}){ // my code function here }
}
new Version
const MyComponent = (props) => {
const myComponentInstance = useRef(null)
const start = ({...config}){ // my code function here }
}
I saw a bit of useRef
, but I don't know if it's right to use it, and how I would make my show method static
doing this, I can call my component's method from another component (it already works with the class)
Ex:
import { Root, myComponent } from 'myComponent'
<Root>
<a onclick="myComponent.show({...})">Show</a>
</Root>
Is it possible to use static methods
with react hooks
?
2 Answers
Reset to default 14You can't use static
but properties and variables still exist
While @Clarity is right that you can't use static methods/properties with function based React components, a static method/property is, for your intents and purposes, the equivalent of a function/variable.
For one, you could simply attach the method and properties to your MyComponent
like so:
MyComponent.myComponentInstance = null
MyComponent.show = function() {}
// Using function keyword allows you to use the `this` keyword to reference MyComponent
There are other options than OOP
The other option is to simply create variables/functions and export them. This will take advantage of the module system the same way you would by exporting your components.
export let myComponentInstance
export function show () {}
Then, to use them, you can import them:
import { myComponentInstance, show } from './example.js'
You cannot use React Hooks in class components at all, that means that static
cannot be used with hooks either.
More info is in the Rules of Hooks.
static
method refers tothis
that makes no sense to me. what's a goal? could you describe business meaning or data flow? – skyboyer Commented Sep 23, 2019 at 20:13