Search code examples
stenciljs

StencilJS trying to set component's internal input tag state according to Prop input


I'm building a custom input tag with stenciljs and I dont understand how to set the inputs disabled or readonly state. I'm passing the property to the component from the parent as an enum with 3 properties as follows:

enum INPUT_STATE {
  DISABLED = "disabled",
  READONLY = "readonly",
  DEFAULT = ""
}


And the component looks as follows:

export class InputFields {

  @Prop() inputState: INPUT_STATE;

  render() {
    return (
      <div class="status">
        <input type="text" {...INPUT_STATE[this.inputState]}/>
      </div>
    );
  }
}

So basically what I'm trying to do is to set the passed property on the input, be it disabled or readonly and an empty string for default state. How can I achieve this functionality?


Solution

  • INPUT_STATE is an enum. The INPUT_STATE values are strings, so INPUT_STATE[this.inputState] is a string not an object. Strings don't map directly to jsx attributes - you would have to set explicitly:

    <input type="text" disabled={this.inputState === INPUT_STATE.DISABLED}/>
    

    By using a watch , you can move the logic out of the JSX:

    private inputStateAttr = {};
      
    @Prop() inputState: INPUT_STATE;
    @Watch('inputState')
    handleInputStateChange(value: INPUT_STATE) {
      this.inputStateAttr = {
        disabled: INPUT_STATE.DISABLED === value,
        readonly: INPUT_STATE.READONLY === value
      };
    }
    
    render() {
      return (
        <div class="status">
          <input type="text" {...this.inputStateAttr}/>
        </div>
      );
    }