christheliz
christheliz

Reputation: 306

Passing props from class component in react + typescript

I am new to typescript and am wondering how to pass the prop from my class component to a parent class.

My child class looks like this:

import React from "react";

type Props = {
startTimeInSeconds: number;
}

type State = {
timeRemainingInSeconds: number;
}


export default class Child extends React.Component<Props, State>{
    private timer: any;

constructor(props: Props) {
  super(props);
  this.state = {
    timeRemainingInSeconds: props.startTimeInSeconds
  };
}

decrementTimeRemaining = () => {
  if (this.state.timeRemainingInSeconds > 0) {
    this.setState({
      timeRemainingInSeconds: this.state.timeRemainingInSeconds - 1
    });
  } else {
    clearInterval(this.timer!);
  }
};

componentDidMount() {
  this.timer = setInterval(() => {
    this.decrementTimeRemaining();
  }, 1000);
}

render() {
  return (
    <div className="countdown-timer">
      <div className="countdown-timer__circle">
        <svg>
          <circle
            r="24"
            cx="26"
            cy="26"
            style={{
              animation: `countdown-animation ${this.props
                .startTimeInSeconds}s linear`
            }}
          />
        </svg>
      </div>
      <div className="countdown-timer__text">
        {this.state.timeRemainingInSeconds}s
      </div>
    </div>
  );
}
}

I wanted to call this child component in my parent component but I don't get how it is working. I tried to call the child within the parent with

<Child startTimeInSeconds = { this.startTimeInSeconds } />

but it throws an error.

A (simplified) parent component looks like this:

import '../css/App.css';
import * as React from "react";
import Child from "./ChildComponent"

function App(props) {
  return (
    <>
    <div>
        <Child startTimeInSeconds = { this.startTimeInSeconds } />
    </div>
    </>
  );
}

export default App;

Upvotes: 2

Views: 5762

Answers (1)

Gulam Hussain
Gulam Hussain

Reputation: 1763

Your Child component is fine, but you are passing incorrect props to it.

In App component you need to define startTimeInSeconds variable>

You parent component should look like this -

import '../css/App.css';
import * as React from "react";
import Child from "./ChildComponent"

function App(props) {
  const startTimeInSeconds = 0; //or any number
  return (
    <>
    <div>
        <Child startTimeInSeconds = { startTimeInSeconds } />
    </div>
    </>
  );
}

export default App;

Upvotes: 2

Related Questions