Conditional Properties Using React with TypeScript

In React with TypeScript, conditional properties allow you to pass props to components only when certain conditions are met. This technique is essential for creating dynamic, interactive user interfaces that respond to state changes and user interactions.

TypeScript enhances this pattern by providing type safety, ensuring that your conditional props are correctly typed and helping catch potential runtime errors during development.

Understanding Conditional Properties

Conditional properties are props that are only set on a component under specific conditions. In React with TypeScript, you can implement this using:

  • Ternary operator - Returns one value if condition is true, another if false

  • Logical AND (&&) operator - Renders content only when condition is truthy

  • Conditional statements - Using if/else logic to determine prop values

Setting Up the Project

Create a new React TypeScript project:

npx create-react-app my-app --template typescript

Basic Example: User Information Display

This example demonstrates conditional rendering based on user data. We'll display user ID and username conditionally based on their values.

MyComponent.tsx

import React from 'react'

type Props = {
   userId: number
   username: string
}

const MyComponent: React.FC<Props> = ({ userId, username }) => {
   return (
      <div style={{ border: '1px solid black', padding: '5px', margin: '5px 0' }}>
         {userId !== 0 ? <p>User ID: {userId}</p> : <p>User ID Not Defined!</p>}
         {username !== '' && <p>Username: {username}</p>}
      </div>
   )
}

export default MyComponent

App.tsx

import React from 'react'
import MyComponent from './MyComponent'

const App: React.FC = () => {
   return (
      <div style={{ padding: '10px' }}>
         <h2>Conditional Properties Using React with TypeScript</h2>
         
         <h4>userId: 123, username: 'ABC'</h4>
         <MyComponent userId={123} username="ABC" />

         <h4>userId: 456, username: ''</h4>
         <MyComponent userId={456} username="" />

         <h4>userId: 0, username: 'XYZ'</h4>
         <MyComponent userId={0} username="XYZ" />

         <h4>userId: 0, username: ''</h4>
         <MyComponent userId={0} username="" />
      </div>
   )
}

export default App

Interactive Example: Dynamic State Management

This example shows how to use conditional properties with state management, creating an interactive interface that responds to user actions.

InteractiveComponent.tsx

import React from 'react'

type Props = {
   showMessage: boolean
   showAlert: boolean
   count: number
}

const InteractiveComponent: React.FC<Props> = ({ showMessage, showAlert, count }) => {
   return (
      <div style={{ padding: '5px' }}>
         {showMessage && (
            <p style={{ backgroundColor: '#afe7af', padding: '10px', borderRadius: '4px' }}>
               Good Morning! Welcome to our app.
            </p>
         )}
         {showAlert && (
            <p style={{ backgroundColor: '#ffbaba', padding: '10px', borderRadius: '4px' }}>
               This is an alert message!
            </p>
         )}
         <h4>Current Count: {count}</h4>
      </div>
   )
}

export default InteractiveComponent

App.tsx

import React, { useState } from 'react'
import InteractiveComponent from './InteractiveComponent'

const App: React.FC = () => {
   const [showMessage, setShowMessage] = useState<boolean>(false)
   const [showAlert, setShowAlert] = useState<boolean>(false)
   const [count, setCount] = useState<number>(0)

   return (
      <div style={{ padding: '10px' }}>
         <h2>Interactive Conditional Properties</h2>
         
         <div style={{ marginBottom: '20px' }}>
            <button 
               onClick={() => setShowMessage(!showMessage)}
               style={{ margin: '5px', padding: '8px 16px' }}
            >
               {showMessage ? 'Hide' : 'Show'} Message
            </button>
            
            <button 
               onClick={() => setShowAlert(!showAlert)}
               style={{ margin: '5px', padding: '8px 16px' }}
            >
               {showAlert ? 'Hide' : 'Show'} Alert
            </button>
            
            <button 
               onClick={() => setCount(count + 1)}
               style={{ margin: '5px', padding: '8px 16px' }}
            >
               Increase Count
            </button>
            
            <button 
               onClick={() => setCount(count - 1)}
               style={{ margin: '5px', padding: '8px 16px' }}
            >
               Decrease Count
            </button>
         </div>

         <InteractiveComponent
            showMessage={showMessage}
            showAlert={showAlert}
            count={count}
         />
      </div>
   )
}

export default App

Key Patterns

Pattern Use Case Example
Ternary Operator Choose between two values {userId ? `ID: ${userId}` : 'No ID'}
Logical AND (&&) Show content only if condition is true {isLoggedIn && <Profile />}
Conditional Props Pass props based on conditions <Button disabled={!isValid} />

TypeScript Benefits

  • Type Safety - Ensures props match expected types

  • IntelliSense - Better autocomplete and error detection

  • Refactoring Support - Safer code changes across components

  • Documentation - Type definitions serve as inline documentation

Conclusion

Conditional properties in React with TypeScript provide a powerful way to create dynamic, type-safe user interfaces. By leveraging TypeScript's type system with React's conditional rendering patterns, you can build robust applications that are both maintainable and error-resistant.

Updated on: 2026-03-15T23:19:00+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements