'Conditional render + add some extra code in React
I'm aware of some of the conditional rendering methods for React components. Some of them can be found here.
Using ternary operatiors, if...elses.... But I want to know if theres a way to render a component based on a condition and perform some calculations before rendering.
A normal conditional render will look like this:
<>
{myCondition && (<MyComponent /)}
</>
But what I need to know if it's possible to do, is something like this
<>
{myCondition &&
const myVars = 'Some random vars I need'; // try to gather some info before rendering the component
return <MyComponent vars={myVars} />
}
</>
Is there a way to perform this operation before rendering?
Solution 1:[1]
You can use useState, useEffect hooks and some if operators like this:
const [myVars, SetMyVars] = useState("")
const [myCondition, SetMyCondition] = useState(false)
useEffect(() => {
if(myCondition) {
SetMyVars("something")
}
},[myCondition])
return (
{myCondition && <MyComponent vars={myVars} /> }
)
and then you can add some code to change your condition and etc.
Solution 2:[2]
the best way to render content conditionally is by defining a helper function and calling it right away.
import React from 'react'
const renderContent = ()=>{
// add some logic here
// all sort of things you can imagine
// include if statements containing return statements
}
function tryThis() {
return (
<div>{renderContent()}</div>
)
}
export default tryThis
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | remarkablejames |
