Hey!
I've been learning React recently, and handling error messages separately in my React Project, and wondered 🤔:
"What if you can merge them together?"
So I tried this:
useErrors.js
It's pretty self-explanatory, but essentially I define a useErrors
function that creates an error
state. Then, within that same function, I create an Error
Component, which checks if an error exists. If no error exists, it is set to false; any other value would mean that there is an error.
Thus, the Error
Component renders accordingly, and the useErrors
function returns that Error
Component, along with the setError
function.
Usage:
test.js
The useErrors
function is handled 4 ways:
import useErrors from "./useErrors";
- imports the function.
const [Error, setError] = useErrors(false);
- creates the Error state, passing in the default error value (a value of false is automatically hidden), and returns the Error
Component, as well as the setError
function.
setError([<value> | false);
- invokes the function to set the error message. A value of false is hidden; any other value is displayed as the error message.
<Error />
- the JSX to render the error message. (Notice no props are sent, yet it works?)
When running the code, the error is displayed:
And, when ready, it can be closed (which just sets the error
state to false)
More Testing:
To further test, we can create a loop that sets random error messages and clears them:
test.js
It even works when you create multiple Error
States (different names for different messages), and you could reuse the same Error
Component multiple times on the page and it'll React the same for that setError
:
But... how? Why?
From my understanding, React Components
are reusable, either if they're functional or class-based. And the usual way data is sent/updated per Component is either through state
or props
. So how does a variable from a parent function run down into that Component, while being unique to that one instance of error message?
Until I've successfully created commenting on posts to this website, you can find me on Twitter @danidre or join my Discord server. Feel free to message me on the Nodeiflux server and share your thoughts!