I'm using TypeScript and React to try to implement my custom types in React component. However the component is not re-rendering if data members of object in state has updated.
Here's my code:
class Person {
name: string;
surname: string;
constructor(name: string, surname: string) {
this.name = name;
this.surname = surname;
}
}
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
persons: [new Person("Alpha", "A"), new Person("Bravo", "B")]
};
}
render() {
return (
<div>
<button
onClick={() => {
this.state.persons[0].name = "Zulu";
this.state.persons[0].surname = "Z";
}}
>
Change A to Z
</button>
<button
onClick={() => {
this.setState({
persons: [...this.state.persons, new Person("Charlie", "C")]
});
}}
>
Add C
</button>
<button onClick={() => { this.forceUpdate(); }}> Force Update </button>
{this.state.persons.map(person => (
<p>
{person.name} {person.surname}
</p>
))}
</div>
);
}
}
If I click on Change A to Z nothing will change - unless Add C or Force Update is clicked. I am assuming React cannot detect changes made in Person therefore no re-render.
I have some questions about this problem.
- Is this approach (custom datatype as state) recommended to use in React
- If yes - how do I make this work? (React able to detect changes made in
Person) - If no - what is the recommended approach to use custom datatype in React?
- If yes - how do I make this work? (React able to detect changes made in