Câu hỏi phỏng vấn Reactjs
Câu hỏi

What are inline conditional expressions in ReactJS?

Câu trả lời

Inline conditional expressions in ReactJS are techniques used within JSX to conditionally render components or elements based on certain conditions. These expressions allow developers to write cleaner and more concise code by embedding conditions directly within the JSX, rather than using more verbose conditional statements like if-else blocks outside of the JSX.

Inline If-Else with Ternary Operator

The ternary operator is a common inline conditional expression in React. It takes three operands: a condition, a value if the condition is true, and a value if the condition is false. It is written as condition ? trueValue : falseValue. This operator is particularly useful for rendering one of two components depending on a boolean condition. For example:

const isLoggedIn = true;
return (
  <div>
    {isLoggedIn ? <LoggedInComponent /> : <LoggedOutComponent />}
  </div>
);

In this example, <LoggedInComponent /> is rendered if isLoggedIn is true, otherwise <LoggedOutComponent /> is rendered[1][2][6].

Inline If with Logical AND Operator

Another method for inline conditional rendering in React uses the logical AND (&&) operator. This operator checks if the condition on its left side is true; if it is, React will render the JSX or component on its right side. If the condition is false, React will ignore and skip rendering the component. This is useful for rendering components only when certain conditions are met, without having to specify an alternative for when the condition is false. For...

junior

junior

Gợi ý câu hỏi phỏng vấn

junior

What's the difference between a Controlled component and an Uncontrolled one in React?

middle

What's the typical pattern for rendering a list of components from an array in React?

middle

What's the difference between useRef and createRef ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào