Rules Hub
Coding Rules Library
Extract derived values into named variables
Compute derived values (like URLs, labels, or config) in the component body instead of embedding logic or anonymous functions inside JSX props.
Bad example
| 1 | const DownloadButton = ({ platform }: Props) => { |
| 2 | return ( |
| 3 | <button |
| 4 | onClick={() => { |
| 5 | // Logic hidden inside an anonymous handler |
| 6 | const url = platform === 'ios' |
| 7 | ? 'https://apps.apple.com/app' |
| 8 | : 'https://play.google.com/store/app'; |
| 9 | window.open(url, '_blank'); |
| 10 | }} |
| 11 | > |
| 12 | Download App |
| 13 | </button> |
| 14 | ); |
| 15 | }; |
Explanation (EN)
Defining logic inside the JSX prop (especially anonymous functions) mixes calculation with presentation. It makes the component harder to read and the URL calculation cannot be reused or easily tested.
Objašnjenje (HR)
Definiranje logike unutar JSX propsa (posebno anonimnih funkcija) miješa izračune s prezentacijom. To otežava čitanje komponente, a izračun URL-a se ne može ponovno iskoristiti ili lako testirati.
Good example
| 1 | const DownloadButton = ({ platform }: Props) => { |
| 2 | // Logic extracted into a clear, descriptive variable |
| 3 | const appUrl = platform === 'ios' |
| 4 | ? 'https://apps.apple.com/app' |
| 5 | : 'https://play.google.com/store/app'; |
| 6 |
|
| 7 | return ( |
| 8 | // Clean, declarative JSX |
| 9 | <a |
| 10 | href={appUrl} |
| 11 | target="_blank" |
| 12 | rel="noopener noreferrer" |
| 13 | > |
| 14 | Download App |
| 15 | </a> |
| 16 | ); |
| 17 | }; |
Explanation (EN)
The derived value (`appUrl`) is calculated once in the render body, making the JSX declarative and clean. This clarifies the intent and separates business logic from the UI structure.
Objašnjenje (HR)
Izvedena vrijednost (`appUrl`) izračunava se jednom u tijelu komponente, čineći JSX deklarativnim i čistim. To pojašnjava namjeru i odvaja poslovnu logiku od UI strukture.