I’m trying to update (setState) a React functional component from within “regular” (vanilla) JavaScript.
I searched through StackOverflow but all the answers deal with passing data from React to (vanilla) JavaScript, and not the other way around.
Let’s take the example from the docs:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
To render it in JavaScript, I do:
<script>
let example = ReactDOM.render(
<Example />,
document.getElementById('example-wrapper')
);
</script>
Now suppose I want to manually update the count from the vanilla JavaScript code, outside of react. Like:
<script>
function updateExampleCount(newCount) {
example.setCount(newCount); // ???
}
</script>
I can’t access the component state, as setCount is a private variable inside the function, and example
returned from render
is null
.
If I use a class component, then render
returns a reference to the component and then I can call example.setState
. But I prefer not to convert my component into a class if I can avoid it.
The docs for render
say:
Render a React element into the DOM in the supplied container and return a reference to the component (or returns null for stateless components).
But my component does have a state (count), it just doesn’t recognize it.
If it’s not possible to use the return value from render
, is there another way to “get” the component and then use setCount (or some other way to set the state)?
Or do I just have to use a class component for this?
Thanks.