I have a problem with conditional rendering in reactjs.
If an environment is prod, then <Sentry.ErrorBoundary> tag should be loaded.
Is there a better way instead of using if with sentrytag and else without sentrytag?
ReactDOM.render(
<Provider store={store}>
{environment == 'PROD' && <Sentry.ErrorBoundary> }
<Experiment>
<Root />
</Experiment>
{environment == 'PROD' && </Sentry.ErrorBoundary> }
</Provider>, document.getElementById('root'));
Is there a better way instead of using
ifwithsentrytagandelsewithoutsentrytag
Yea you could define a variable with the 'wrapper' element, or an 'empty' React.Fragment if the element isn't needed:
const wrapper = (environment === 'PROD') ? Sentry.ErrorBoundary : React.Fragment;
<Provider store={store}>
<wrapper>
<Experiment>
<Root />
</Experiment>
</wrapper>
</Provider>
Small working demo, just to give the idea.
The Error component is the Sentry.ErrorBoundary in OP's example.
Press the button to toggle the 'error' state to enable/disable the wrapper.
const Error = (props) => (
<div>
<h1>{'Omg; error!'}</h1>
{props.children}
</div>
);
const Example = () => {
const [ err, setErr ] = React.useState(true);
const Wrapper = (err) ? Error : React.Fragment;
return (
<div>
<Wrapper>
Hello!
</Wrapper>
<br /><br /><br />
<button onClick={() => setErr(!err)}>Toggle</button>
</div>
)
}
ReactDOM.render(<Example />, document.getElementById("app"));
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="app"></div>