TransWikia.com

The Data Flows Down in React.js

Stack Overflow Asked by Fahd Dev on November 4, 2021

Hi Im just learning react
I’ve small problem

I want to learn how to pass state data to its Child as props

Here’s me code

App.js

import React from "react";
import Clock from "./Clock";
import Test from "./Test";

import "./App.css";

function App() {
  return (
    <div className="App">
      <Clock />,
      <Test />
    </div>
  );
}

export default App;

Clock.js

import React from "react";
import Test from "./Test";


class Clock extends React.Component {
  state = {
    date: new Date(),
  };

 

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }
 
  tick() {
    this.setState({
      date: new Date(),
    });
  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
        <h3> Time Now</h3>
       <Test date={this.state.date} />
           </div>
    );
  }
}

export default Clock;

Here’s the Child component I want to pass the state I named it test

import React, { Component } from "react";

export class Test extends Component {
  render() {
    return (
      <div>
        <p>{this.props.date.toLocaleTimeString()}</p>
      </div>
    );
  }
}

export default Test;

I got this error >>

TypeError: Cannot read property ‘toLocaleTimeString’ of undefined
date undefined although I gave its parent props



Please I need help
thanks in advanced

2 Answers

You've passed props perfectly in Clock.js however in App.js you are not passing date as a prop to <Test /> which is why you're getting the above error.

Answered by Pranav on November 4, 2021

I guess you are seeing the error because of Test Instance used in App.js. You are not passing in data over there. Removing it from there may get rid of error.

App.js

import Clock from "./Clock";

import "./App.css";

function App() {
  return (
    <div className="App">
      <Clock />
    </div>
  );
}

export default App;

Answered by Yash Joshi on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP