Home > Article > Web Front-end > Conditional properties using React with TypeScript
In React with TypeScript, you can use conditional rendering to select what to render based on conditions. 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 using TypeScript. One way is to use the conditional operator (also called the ternary operator). This operator accepts a condition and returns a value if the condition is true or another value if the condition is false.
You can also conditionally render components based on conditions using the && operators. The operator evaluates to true if the value on the left side of the operator is true; if the value on the left side of the operator is false, the operator evaluates to false.
Another way to implement conditional rendering is to use a switch statement, which allows you to test a value for multiple conditions and execute different blocks of code depending on which condition matches the value.
Generally speaking, when implementing conditional rendering, it is best to use the most straightforward method that meets your needs. This can make the code easier to read and understand.
In React, properties pass data from parent components to child components. Conditional properties are only set on a component under certain conditions.
By using TypeScript with React, you can type-check your code and provide type definitions for the properties your components expect to receive. This can help catch errors 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 the ternary operator to set the value of a property based on a condition. For example, you might have a component that requires a "color" property, but you only want to set the "color" property when a specific condition is met. In this case, you can use a conditional statement to set the 'color' property only when the condition is met.
Create a new React TypeScript project using the following command -
npx create-react-app my-app --template typescript
Create a new component named "MyComponent" in the src folder of the React project, named "MyComponent.tsx".
Then we need to define the Props interface to use TypeScript data conventions in React.
We can conditionally display the passed properties using the ternary operator or the && operator.
From "App.tsx", we import MyComponent and use it multiple times. We use the component with different property values and check the results on the web page.
In this example, we demonstrate conditional properties using React and TypeScript. We get the property values in MyComponent through props. We take two attributes, "userId" and "username". Logically, if useId is not equal to 0, we try to display the userId on the web page using the ternary operator and use the && operator to display the username only if the username is not an empty string.
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
In this example, we will see conditional properties more efficiently and interactively. We will accept user input to display messages and data on the web page. We take three properties: "showMessgae", "showAlert" and "count". Logically, we will pass these properties dynamically in MyComponent using user-triggered events. In App.tsx we have four buttons "Show Message", "Show Alert", "Increase Count" and "Decrease Count". We also have some states in App.tsx for displaying messages, alerts and storing counter values. Logically, we are switching state to change properties in 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
Click the "Show Message" button
Click the "Show Alert" button
Click the "Increase Count" button
Click the "Reduce Count" button
Conditional properties using React and TypeScript are a very powerful and interactive way to build any web application. This is a necessity for modern web development.
The above is the detailed content of Conditional properties using React with TypeScript. For more information, please follow other related articles on the PHP Chinese website!