Skip to content

Commit 5bfab18

Browse files
authored
Update react.md
1 parent 976ba88 commit 5bfab18

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

docs/jsx/react.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,49 @@ const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag
150150
const foo = <T extends {}>(x: T) => x;
151151
```
152152
153+
### React Tip: Strongly Typed Refs
154+
You basically initialize a variable as a union of the ref and `null` and then initiazlie it as as callback e.g.
155+
156+
```ts
157+
class Example extends React.Component {
158+
example() {
159+
// ... something
160+
}
161+
162+
render() { return <div>Foo</div> }
163+
}
164+
165+
166+
class Use {
167+
exampleRef: Example | null = null;
168+
169+
render() {
170+
return <Example ref={exampleRef => this.exampleRef = exampleRef } />
171+
}
172+
}
173+
```
174+
175+
And the same with ref's for native elements e.g.
176+
177+
```ts
178+
class SelfFocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{
179+
input: HTMLInputElement | null = null;
180+
181+
render() {
182+
return (
183+
<input
184+
ref={(input) => this.input = input}
185+
value={this.props.value}
186+
onChange={(e) => { this.props.onChange(this.ctrls.input.value) } }
187+
/>
188+
);
189+
}
190+
componentDidMount() {
191+
this.input.focus();
192+
}
193+
}
194+
```
195+
153196
### Type Assertions
154197
155198
Use `as Foo` syntax for type assertions as we [mentioned before](./type-assertion.md#as-foo-vs-foo).

0 commit comments

Comments
 (0)