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

How to conditionally add att...

Câu trả lời

To conditionally add attributes to React components, you can use several approaches depending on the specific requirements and the complexity of the condition. Here are some common methods:

1. Using Ternary Operators

A ternary operator can be used to conditionally render attributes based on a condition. This is useful for simpler conditions.

const MyComponent = ({ isDisabled }) => {
  return <input type="text" disabled={isDisabled ? true : undefined} />;
};

2. Using Logical AND Operator

For attributes that you want to add only if a condition is true, you can use the logical AND (&&) operator. This method is clean and concise for straightforward conditions.

const MyComponent = ({ shouldFocus }) => {
  return <input type="text" {...(shouldFocus && { autoFocus: true })} />;
};

3. Using Object Spread with Conditions

When dealing with multiple conditional attributes, or when the conditions are more complex, you can use an object spread syntax. This allows for more dynamic and readable code.

const MyComponent = ({ isActive, isDisabled }) => {
  const additionalProps = {
    ...(isActive && { className: 'active' }),
    ...(isDisabled && { disabled: true })
  };

  return <button {...additionalProps}>Click me</button>;
};

4. Inline Conditional Expressions

For inline conditions, especially when you need to toggle between two possible values for an attribute, you can use a ternary operator directly in the attribute.

const MyComponent = ({ isEditable }) => {
  return <input type="text" readOnly={isEditable ? false : true} />;
};

5. Function to Determine Attributes

For more complex conditions or when dealing with a large number of conditional attributes, you can abstract the logic into a function that returns the attributes object.

const getAttributes = (isDisabled, isActive) => ({
  ...(isDisabled && { disabled: true }),
  ...(isActive && { className: 'active' })
});

const MyCompon...
senior

senior

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

senior

When shall we use useReducer hook in ReactJS?

expert

How to use React.memo() ?

senior

When to use useCallback , useMemo and useEffect ?

Bình luận

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

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