Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
reacterror-handlingrobustnessjsxclean-code

Handle fallible derivations safely outside JSX

Wrap logic that might throw errors (like URL parsing) in safe handlers outside JSX to prevent component crashes.

PR: Feat/FCK-1669 - Adding Job Landing Page #3656Created: Dec 8, 2025

Bad example

Old codetsx
1const CompanyLink = ({ url }: { url: string }) => (
2 <div>
3 {/* If 'url' is invalid string, new URL() throws and crashes the app */}
4 <a href={new URL(url).href} target="_blank">
5 Visit Website
6 </a>
7 </div>
8);

Explanation (EN)

Calling functions that can throw exceptions (like `new URL()`) directly inside JSX is unsafe. If the input is invalid, the error will bubble up and unmount the entire component tree (or crash the app), offering no fallback UI.

Objašnjenje (HR)

Pozivanje funkcija koje mogu baciti iznimke (poput `new URL()`) izravno unutar JSX-a nije sigurno. Ako je ulaz neispravan, greška će srušiti cijelu komponentu (ili aplikaciju) bez mogućnosti prikaza rezervnog sučelja.

Good example

New codetsx
1const safeUrl = (url: string) => {
2 try {
3 return new URL(url).href;
4 } catch {
5 return null;
6 }
7};
8
9const CompanyLink = ({ url }: { url: string }) => {
10 // Derive safely in the body before rendering
11 const normalizedUrl = safeUrl(url);
12
13 if (!normalizedUrl) return null;
14
15 return (
16 <div>
17 <a href={normalizedUrl} target="_blank">
18 Visit Website
19 </a>
20 </div>
21 );
22};

Explanation (EN)

The fallible logic is extracted into a helper function with a try-catch block, and the result is computed in the component body. This ensures that invalid data simply results in the element not rendering (or rendering a fallback) rather than a crash.

Objašnjenje (HR)

Logika koja može uzrokovati grešku izdvojena je u pomoćnu funkciju s `try-catch` blokom, a rezultat se izračunava u tijelu komponente. Time osiguravamo da neispravni podaci rezultiraju skrivanjem elementa (ili prikazom rezerve) umjesto rušenjem aplikacije.