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.

jsx Copy
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.

jsx Copy
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.

jsx Copy
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.

jsx Copy
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.

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

const MyCompon...
senior

senior

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

expert

How to avoid the need for binding in React?

junior

What are advantages of using React Hooks?

senior

What is the purpose of super(props) ?

Bình luận

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

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