I am trying to use react to recreate my currents components (written in pure typescript) but I can't find a way to give additional props to a component extending an other.
export interface DataTableProps { columns: any[]; data: any[]; } export class DataTable extends React.Component<DataTableProps, {}> { render() { // -- I can use this.props.columns and this.props.data -- } } export class AnimalTable extends DataTable { render() { // -- I would need to use a this.props.onClickFunction -- } }
My problem is that I need to give AnimalTable some props that would be irrelevant to DataTable. How can I do that ?
Implement Inheritance in ReactUsing the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component. This example creates one component called ParentClass. jsx. ParentClass extends the component from React as React.
To extend an HTML Element in a component's props in React, extend the specific element type in the props interface of your component, e.g. interface ButtonProps extends React. ButtonHTMLAttributes<HTMLButtonElement> {} . Copied! import React from 'react'; interface ButtonProps extends React.
A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.
To change state in a class component use the setState method. This method enqueues changes in the state and causes a component to re-render. Set Another Value!
You'll need to make DataTable
generic so that you'll be able to use an interface which extends DataTableProps
:
export interface AnimalTableProps extends DataTableProps { onClickFunction: Function; } export class DataTable<T extends DataTableProps> extends React.Component<T, {}> { } export class AnimalTable extends DataTable<AnimalTableProps> { render() { // this.props.onClickFunction should be available } }
For those who need, base classes can declare required/abstract methods that all instances must implement:
import { Component } from 'react' abstract class TestComponent<P = {}, S = {}, SS = any> extends Component<P, S, SS> { abstract test(): string } type Props = { first: string, last: string, } type State = { fullName: string, } class MyTest extends TestComponent<Props, State> { constructor(props: Props) { super(props) this.state = { fullName: `${props.first} ${props.last}` } } test() { const { fullName } = this.state return fullName } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With