search

Home  >  Q&A  >  body text

How to dynamically add properties based on conditions in React components?

<p>Is there a way to add properties to a React component only when certain conditions are met? </p> <p>I need to add required and readOnly attributes to the form element based on conditions in the post-rendered Ajax call, but I don't know how to solve this problem because <code>readOnly="false"</code> is completely different from Omitting attributes is different. </p> <p>The example below should illustrate what I want, but it doesn't work. </p> <blockquote> <p>(Parse error: unexpected identifier)</p> </blockquote> <pre class="brush:js;toolbar:false;">function MyInput({isRequired}) { return <input classname="foo" {isRequired ? "required" : ""} /> } </pre> <p><br /></p>
P粉665427988P粉665427988505 days ago638

reply all(2)I'll reply

  • P粉545218185

    P粉5452181852023-08-21 13:12:17

    juandemarco's answer is usually correct, but there is another option here.

    Construct an object to your liking:

    var inputProps = {
      value: 'foo',
      onChange: this.handleChange
    };
    
    if (condition) {
      inputProps.disabled = true;
    }

    Use spread for rendering, and you can also choose to pass other props.

    <input
        value="这个值会被inputProps覆盖"
        {...inputProps}
        onChange={overridesInputProps}
     />

    reply
    0
  • P粉863295057

    P粉8632950572023-08-21 11:18:48

    Obviously, for some properties, if the value passed to React is not a true value, React will intelligently omit the property. For example:

    const InputComponent = function() {
        const required = true;
        const disabled = false;
    
        return (
            <input type="text" disabled={disabled} required={required} />
        );
    }

    will get:

    <input type="text" required>

    UPDATE: If anyone is curious about how and why this happens, you can find the details in the source code of ReactDOM, specifically in the DOMProperty.js file at page 30 Lines and 167 lines .

    reply
    0
  • Cancelreply