Set Properties on Child Components

To communicate down the containment hierarchy, an owner can set a property on a child component. An attribute in HTML turns into a property assignment in JavaScript.

A parent component can set a primitive value like a string or number on a child component. However, non-primitive value like an object or array passed to a component is read-only and you must make a shallow copy to modify any of the nested values.

Let’s look at how the owner, c-todo-app, sets public properties on the two instances of c-todo-item.

Look at todoItem.js. The @api decorator exposes the itemName field as a public property.

To set the public itemName property, todoApp.html sets the item-name attribute on each c-todo-item component.

Property names in JavaScript are in camel case while HTML attribute names are in kebab case (dash-separated) to match HTML standards. In todoApp.html, the item-name attribute in markup maps to the itemName JavaScript property of c-todo-item.

This example uses static values of Milk and Bread, but a real-world component would typically use a for:each iteration over a collection computed in the owner’s JavaScript file, todoApp.js.

For a slightly more complicated example, see the composition basics recipe in the lwc-recipes repo.

You can also play with similar code in a playground at lwc.dev, which is the Lightning Web Components: Open Source developer site.

A non-primitive value like an object or array that's passed to a component is read-only. To mutate the data, make a shallow copy of the objects you want to mutate.

Let's take a look at a parent component that passes an object to a child component and then let the child component update its value.

Set the value in the JavaScript.

The reactive object obj is passed from the parent component to the child component. The child component displays the serialized object string with two buttons that update the object value either by updating the original object or a shallow copy of it.

The component cannot change the content of the object or array. When you try to update the original object value, an error Uncaught Error: Invalid mutation: Cannot set "msg" on "[object Object]". "[object Object]" is read-only. is thrown since the child component is attempting to mutate a property on the object.

Non-primitive values with references from a parent component, as shown by this.obj, are wrapped in a proxy and can't be modified. However, you can modify its content by creating a shallow copy of the non-primitive.

While this.obj.msg throws an invalid mutation error, the this.obj value assignment in updateShallow() updates the {serializedObj} value on the child component only. The {serializedObj} value on the parent component isn't updated.

See Also