top of page
Logo der Online Agentur mdwp

Coercion

In JavaScript, Coercion means converting a value from one type to another, such as a string to a number or an object to a boolean. This behaviour is commonly seen in JavaScript because it is a dynamically typed language, which means you don't have to declare variable types. They can be changed or "coerced" into another type based on how you use them.

React uses JavaScript, and therefore React developers must be aware of coercion in order to avoid bugs. In React, coercion often comes into play when dealing with the state or the props of a component.

For example:

```jsx
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myNumber: "5"
};
}

render() {
// This will not render "10" as expected, but "55", because myNumber is a string
return <div>{this.state.myNumber + 5}</div>;
}
}
```

This confusion is due to JavaScript’s coercive behavior because it treats the '+' operator as concatenation when one of the operands is a string. If you want it to treat '5' as a number, you can coerce '5' to a number using the Number function:

```jsx
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myNumber: "5"
};
}

render() {
// This will correctly render "10"
return <div>{Number(this.state.myNumber) + 5}</div>;
}
}
```

This way, JavaScript understands that we want to add two numbers, not concatenate a string and a number. Therefore, it coerces the string "5" into a number 5 before trying to perform addition.

bottom of page