Reputation: 2157
interface User {
name: string,
address: string,
active: boolean
}
The problem is -
I can't import interface in child component. Child component interface have to be the type parent component provided. So how can I access component props to define interface.
Upvotes: 1
Views: 4237
Reputation: 4937
The interface that need to be imported need to be explicitly exported from the file where it is declared.
Here is the working example for exporting an interface and importing it in a component:
Interface file - IUser.ts
// File name: IUser.ts
export interface IUser {
name: string,
address: string,
active: boolean
}
Component File - Functional comopnent / React Hook
// File name: MyComponent.tsx
import React, {FunctionComponent} from 'react'
import {IUser} from "../interfaces/IUser"
const MyComponent : FunctionComponent<IUser> = (props) => (
<div>
<div>Name: {props.name}</h2>
<div>Address: {props.address}</div>
<div>Active: {props.active}</div>
</div>
)
export default MyComponent
Component File using Class
// File name: MyComponent.tsx
import React, {Component} from 'react'
import {IUser} from "../interfaces/IUser"
export default class MyComponent extends Component<IUser> {
render() {
return (
<div>
<div>Name: {this.props.name}</h2>
<div>Address: {this.props.address}</div>
<div>Active: {this.props.active}</div>
</div>
)
}
}
Upvotes: 4
Reputation: 11
first you should export your interface like so:
export interface User {
name: string,
address: string,
active: boolean
}
then you can import it wherever you want:
import { User } from 'relative/path/to/interface'
Upvotes: 1