Conditional Properties Using React with TypeScript


In React with TypeScript, you can use conditional rendering to choose what to render based on a condition. This is useful when displaying different content or components based on specific criteria. There are a few different ways to implement conditional rendering in React with TypeScript. One way is to use the conditional operator (also known as the ternary operator). This operator takes a condition and returns one value if the condition is true and another if the condition is false.

You can also use the && operator to render a component based on a condition conditionally. This operator evaluates to true if the value on its left side is true and false if the value on its left side is false.

Another way to implement conditional rendering is to use a switch statement, which allows you to test a value against multiple cases and execute different code blocks depending on the case that matches the value.

In general, it's a good idea to use the most straightforward approach that meets your needs when implementing conditional rendering. This can make the code easier to read and understand.

Conditional Properties

In React, a property passes data from parent to child components. Conditional properties are only set on a component under certain conditions.

Using TypeScript with React allows you to type-check your code and provide type definitions for the properties a component expects to receive. This can help catch bugs and make your code easier to understand and maintain.

To create a conditional property in a React component using TypeScript, you can use an 'if' statement or a ternary operator to set the property's value based on a condition. For example, you might have a component that expects a 'color' prop, but you only want to set the 'color' prop if a specific condition is met. In this case, you can use a conditional statement to set the 'color' prop only if the condition is met.

Steps for Examples

  • Create a new react typescript project using the below command −

npx create-react-app my-app --template typescript
  • Create a new component named ‘MyComponent’ in the src folder of the react project with the name ‘MyComponent.tsx’.

  • Then we need to define the Props interface to use the typescript data conventions in react.

  • We can use ternary operators or && operators to show the passed properties conditionally.

  • From ‘App.tsx’ we import the MyComponent and use it multiple times. We use this component under different property values and check the result on the web page.

Example

In this example, we showed the conditional properties using react and typescript. We get the property values in the MyComponent through props. We are taking two properties, ’ userId’ and ‘username’. Logically we are trying to show the userId on the web page if the useId is not equal to 0 using the ternary operator, and we are showing the username only if it is not an empty string using && operator.

App.tsx

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

export const App: React.FC = () => {
   return (
      <div style={{ padding: '10px' }}>
         <h2> Conditional Properties Using React with TypeScript </h2>
         <div>
            <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>
      </div>
  )
}
export default App

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' }}>
         {userId !== 0 ? <p>User ID: {userId}</p> : <p>User ID Not Defined!</p>}
         {username !== '' && <p>User ID: {username}</p>}
      </div>
   )
}
export default MyComponent

Output

Example

In this example, we will see the conditional properties more effectively and interactively. We will take user inputs to show messages and data on the web page. We are taking three properties, ’showMessgae’, ‘showAlert’, and ‘count’. Logically, we will pass these properties dynamically in the MyComponent using user-triggered events. In the App.tsx, we have four buttons’ Show Message’, ‘Show Alert’, ‘Increase Count’, and ‘Decrease Count’. We also have some states in the App.tsx for showing the message, alert and storing counter values. Logically we are toggling the states for changing the properties in the MyComponent.

App.tsx

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

export 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> Conditional Properties Using React with TypeScript </h2>
         <p>
            <button onClick={() => setShowMessage(!showMessage)}>Show Message</button>       
            <button onClick={() => setShowAlert(!showAlert)}> Show Alert </button>
            <button onClick={() => setCount(count + 1)}> Increase Count </button>
            <button onClick={() => setCount(count + 1)}> Decrease Count </button>
         </p>
         <MyComponent
            showMessage={showMessage}
            showAlert={showAlert}
            count={count}
         />
      </div>
  )
}
export default App

MyComponent.tsx

import React from 'react'

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

const MyComponent: React.FC<Props> = ({ showMessage, showAlert, count }) => {
   return (
      <div style={{ padding: '5px' }}>
         {showMessage && (
            <p style={{ backgroundColor: '#afe7af', padding: '10px' }}>
               Good Morning!
            </p>
         )}
         {showAlert && (
            <p style={{ backgroundColor: '#ffbaba', padding: '10px' }}>
               This is alert message!
            </p>
         )}
         <h4>Count: {count}</h4>
      </div>
   )
}
export default MyComponent

Output

Show Message button is clicked

Show Alert button is clicked

Increase Count button is clicked

The Decrease Count button is clicked

The conditional properties using react and typescript are a very powerful and interactive way to build any web application. For modern web development, it is necessary.

Updated on: 21-Feb-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements