Stencil: how to trigger a re-render

I was playing with stencil but couldn’t get the render method to be executed for a second time when an array in the class changed.

The idea was to create a form, in which input fields could be dynamically added. In my code, the input fields are stored in the inputs array. This array gets populated using a for loop that creates input fields equal to the elements in the numbers array.

When initially rendering everything looks as expected, 3 input fields with one submit button.

I wired the submit button to a method that increases the numbers array with one element. I expected that, due to the change in the numbers array, the render method would have been called and an extra input field would have been added. This is however not the case (=the render method is never called again).

Why is that? And how do I make it work (add an input field when pressing submit)?

@Component({
  tag: 'app-input-form',
  styleUrl: 'app-input-form.scss'
})
export class AppInputForm {

  private numbers = [1, 2, 3];

  handleSubmit(e) {
    e.preventDefault()
    this.numbers = [
      ...this.numbers,
      4
    ];
  }

  handleChange(event) {...}

  render() {
    let inputs: JSX.Element[] = []
    for(let num of this.numbers) {
      inputs = [
        ...inputs,
        <label>
        Name:
        <input type="text" value={num} onInput={() => this.handleChange(event)} />
      </label>
      ];
    }
    
    return (
    <form onSubmit={(e) => this.handleSubmit(e)}>
      {inputs}
    <input type="submit" value="Submit" />
    </form>
    );

  }
}

I’ve not used Stencil, but based off their docs it sounds like you’d add the @State() decorator to numbers.

private @State() numbers = [1, 2, 3];

https://stenciljs.com/docs/decorators#managing-component-state

1 Like

Thank you! I works

I was looking at handling-arrays. Should have read all the docs.