How can I define a method inside a class component in React? - reactjs

I have made a simple digital clock in React. It seems working. However, I wanted to define the callback function inside the setState() separately. But I got an error. Do you know how I can define such a function called tick() outside the componenDidMount? Below is my code
import "./Clock.css";
class Clock extends React.Component {
state = { date: new Date() };
componentDidMount() {
setInterval(() => {
this.setState({ date: new Date() });
}, 1000);
console.log("componentdidmount");
}
render() {
return (
<div className="clock-container">
<h1 className="clock">{this.state.date.toLocaleTimeString()}</h1>
</div>
);
}
}
export default Clock;

Is this what you want it to be like?
tick(){
this.interval = setInterval(() => {
this.setState({ date: new Date() });
}, 1000);
}
componentDidMount() {
this.tick();
console.log('componentdidmount');
}
componentWillUnmount(){
clearInterval(this.interval);
}

Related

Rendering a new component inside componentDidMount - React

I will have to render a new component after all the expected components are loaded. I will need a timeout based on which the the new component has to be rendered. So this new component has to show up after 5 minutes after the page has loaded.
I need to render a component called new_component that extends React.component
public componentDidMount(): void {
if (visited) {
setTimeout(() => {
console.log('Reached the timeout')
//Render the new conponent here. (Not sure how to call the render function of another component here)
}, timeout);
}
Can someone help me call the render function of new_component inside componentDidMount please. i tried new_component.render(). But that does not seem to work.
You can use state to track this.
componentDidMount() {
setTimeout(() => {
this.setState({ showNewComponent: true })
})
}
and in render:
render() {
if (this.state.showNewComponent) {
return <NewComponent />
}
return null
}
You can go with this code, wait and then render new one:
cosnt FIVE_MIN = 5 * 60 * 1000
class Example {
this.state = { isShowComponent: false }
timer
componentDidMount() {
this.timer = setTimeout(() => {
this.setState({ isShowComponent: true })
}, FIVE_MIN)
}
componentWilllUnmount() {
clearTimeout(this.timer)
}
render() {
if (this.state.isShowComponent) return <NewComponent />
return <Component />
}
}
:)
you can render your component by your state.
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {
isTimeout: false,
};
}
componentDidUpdate(prevProps, prevState) {
this.checkTimeout = setTimeout(() => {
this.setState(() => ({isTimeout: true}))
}, 500);
}
componentWillUnmount() {
// clean it up when the component is unmounted.
clearTimeout(this.checkTimeout);
}
render () {
if (isTimeout) {
return (k<h1>time is running out</h1>)
}
return (<h1>hello world.</h1>)
}
}

Arrow function ambguity in ReactJS

class Clock extends React.Component {
constructor(props) {
super(props);
this.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>
</div>
);
}
}
In the above code - I wasn't able to understand the setInterval() line - to be precise the function argument of the setInterval line. I think it is an arrow function- I might be wrong. I replaced it with a regular function setInterval(function(){this.tick()},1000) and got an error saying tick() is not a function. What's happening here?
The this reference is reset when using old-style function() syntax, whereas with => (arrow-functions) the this reference is preserved. You can still use function() but you need to call .bind(this) to "fix" the this reference.
So this:
this.timerID = setInterval(
() => this.tick(),
1000
);
Is equivalent to this:
this.timerID = setInterval(
function() { this.tick(); }.bind(this),
1000
);
You need to do this because setTimeout/setInterval is a member-property of the global (window) object, so inside a setTimeout or setInterval callback the this reference is for window, not the call-site's this.

how manage proper way to implement Countdown Timer for two players in react js?

I am a newbie for react js. how to manage two Countdown timers first start and second is stop after 5-second interval second start and first stop.
it work for single Clock successful but add two clocks then first only start and not stop while second not start I don't know how do this ?.
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
isActive: true
};
}
componentDidMount() {
this.intervalId = setInterval(() => {
this.randomCallObject();
}, 5000);
}
randomCallObject() {
this.setState({
Active: !this.state.isActive
});
}
render() {
let clock= {
time: 150,
isActive:this.state.isActive
}
let clock2= {
time: 100,
isActive:!this.state.isActive
}
return (
<div className="container">
<Clcok ClockData={clock}/>
<Clcok ClockData={clock2}/>
</div>
);
}
}
import React, { Component } from "react";
const TOTAL_MINUTES = 60;
export default class ClockComponent extends Component {
constructor(props) {
super(props);
this.state = {
time: props.ClockData.time,
isActive: props.ClockData.isActive
};
}
componentDidMount() {
const { isActive } = this.state;
if (isActive === true) {
this.intervalId = setInterval(() => {
const { time } = this.state;
if (time > 0) {
this.setState({
time: time - 1
});
}
}, 1000);
}
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
render() {
const { time } = this.state;
let minutes ="" + Math.floor((time % (TOTAL_MINUTES * TOTAL_MINUTES))/ TOTAL_MINUTES);
let seconds = "" + Math.floor(time % TOTAL_MINUTES);
if (isNaN(minutes) || isNaN(seconds)) {
return null;
}
if (minutes.length === 1) {
minutes = `0${minutes}`;
}
if (seconds.length === 1) {
seconds = `0${seconds}`;
}
return (
<div className="row">
<div className="col-md-1">
<div>
{minutes}:{seconds}
</div>
</div>
</div>
);
}
}
when clock data comes from props so take simple objects when isActive flag is true then clock timer on when isActive false then timer stop
To learn how to handle setInterval with React, I suggest you read the following blog post by Dan Abramov:
Making setInterval Declarative with React Hooks
In it, he explains how to use setInterval using React Hooks and also how to do it using a class component. On the post, there is also a link to a CodeSandbox example where you can see it in action.
What I did was create another CodeSandbox where you can see how you could apply this example to run multiple timers:
https://codesandbox.io/embed/timers-l6me1
I've used React Hooks in the example because they don't require a lot of code.
I hope it helps.
edit #1
Here is an example of a Counter component taken directly from the mentioned article, and adapted to fit the latter example.
class Counter extends React.Component {
state = {
count: 0,
delay: 1000,
isRunning: true
};
constructor(props) {
super(props);
this.state = { ...this.state, ...props };
}
componentDidMount() {
this.interval = setInterval(this.tick, this.state.delay);
}
componentDidUpdate(prevProps, prevState) {
if (prevState.delay !== this.state.delay) {
this.startInterval();
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
startInterval = () => {
clearInterval(this.interval);
this.interval = setInterval(this.tick, this.state.delay);
console.log(this.interval);
};
tick = () => {
this.setState({
count: this.state.count + 1
});
};
handleDelayChange = e => {
this.setState({ delay: Number(e.target.value) });
};
toggleCounter = () => {
console.log(this.state.isRunning);
if (this.state.isRunning) {
clearInterval(this.interval);
} else {
this.startInterval(this.state.delay);
}
this.setState({
count: 0,
isRunning: !this.state.isRunning
});
};
render() {
const {
state: { isRunning, delay, count },
toggleCounter,
handleDelayChange
} = this;
return (
<>
<h1>{count}</h1>
<input value={delay} onChange={handleDelayChange} />
<button onClick={toggleCounter}>{isRunning ? "stop" : "start"}</button>
</>
);
}
}

setState inside constructor not working properly: ReactJS

I'm trying to run the below code in React+Redux but am running into an unhandled
exception 'NodeInvocationException: Cannot read property 'showText' of
null TypeError: Cannot read property 'showText' of null'
import * as React from 'react';
import { NavMenu } from './NavMenu';
import { Component } from 'react';
export interface BlinkState
{
showText: boolean;
text: '';
}
type BlinkProps = BlinkState;
class Blink extends React.Component<BlinkProps, BlinkState> {
constructor(props: BlinkProps) {
super(props);
//this.state = { showText: true };
this.setState({ showText: true, text: props.text });
// Toggle the state every second
setInterval(() => {
this.setState(previousState => {
return { showText: !previousState.showText };
});
}, 1000);
}
render() {
let display = this.state.showText ? this.props.text : ' ';
return <div>{ display }</div>;
}
}
export class Layout extends React.Component<{}, {}> {
public render() {
return <div className='container-fluid'>
<Blink showText=false text='I love to blink' />
</div>;
}
}
I'm just trying to figure out how to render the Blink copmonent with the props passed in...
You missed the basic thing, use of constructor and setState, use of constructor is to initialize the state value and use of setState is to update the state value, so using setState inside `constructor doesn't makes any sense.
Better way will be, initialise the state in constructor and to run the time use componentDidMount lifecycle method, also don't forgot to stop the time before unmounting the component, to clear it use componentWillUnmount lifecycle method.
Write the component like this:
class Blink extends React.Component<BlinkProps, BlinkState> {
constructor(props: BlinkProps) {
super(props);
this.state = { showText: false };
}
componentDidMount(){
this.timer = setInterval(() => {
this.setState(previousState => {
return { showText: !previousState.showText };
});
}, 1000);
}
componentWillUnmount(){
clearInterval(this.timer)
}
render() {
let display = this.state.showText ? this.props.text : ' ';
return <div>{ display }</div>;
}
}
Working code:
class Blink extends React.Component {
constructor(props) {
super(props);
this.state = { showText: true, text: props.text };
}
componentDidMount(){
this.timer = setInterval(() => {
this.setState(prev => {
return { showText: !prev.showText };
});
}, 1000);
}
componentWillUnmount(){
clearTimer(this.timer)
}
render() {
let display = this.state.showText ? this.props.text : ' ';
return <div>Hello { display }</div>;
}
}
class Layout extends React.Component{
render() {
return <div className='container-fluid'>
<Blink text='I love to blink' />
</div>;
}
}
ReactDOM.render(<Layout/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
You should not specify actions to be taken in the constructor or use setState there, constructor should be used to simply set an initial state.
Also you might need to update the state text since its being set based on props. Do it in the componentWillReceiveProps.
Also when you are using setInterval, make sure to clearInterval when the componentUnmounts
constructor(props: BlinkProps) {
super(props);
this.state = { showText: true, text: props.text };
}
componentWillReceiveProps(nextProps) {
this.setState({text: nextProps.text});
}
componentDidMount() {
// Toggle the state every second
this.interval = setInterval(() => {
this.setState(previousState => {
return { showText: !previousState.showText };
});
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval)
}

react native show current time and update the seconds in real-time

I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don't update unless I refresh the page.
I also tried using setInterval function in render(), it do got update but it's expensive for CPU. is there a good method to realise the function?
state = {
curTime: null,
}
render(){
setInterval(function(){this.setState({curTime: new Date().toLocaleString()});}.bind(this), 1000);
return (
<View>
<Text style={headerStyle.marginBottom15}>Date: {this.state.curTime}</Text>
</View>
);
}
Just move setInterval into componentDidMount function.
Like this :
componentDidMount() {
setInterval(() => {
this.setState({
curTime : new Date().toLocaleString()
})
}, 1000)
}
This will change state and update every 1s.
in react hooks, it can be done like this:
import React, { useState, useEffect } from "react";
const [dt, setDt] = useState(new Date().toLocaleString());
useEffect(() => {
let secTimer = setInterval( () => {
setDt(new Date().toLocaleString())
},1000)
return () => clearInterval(secTimer);
}, []);
This method works fine and displays MM/DD/YY hh:mm:ss format
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
time: new Date().toLocaleString()
};
}
componentDidMount() {
this.intervalID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
tick() {
this.setState({
time: new Date().toLocaleString()
});
}
render() {
return (
<p className="App-clock">
The time is {this.state.time}.
</p>
);
}
}
original link : https://openclassrooms.com/courses/build-web-apps-with-reactjs/build-a-ticking-clock-component
I got the answer. The code below also works.
componentWillMount(){
setInterval(function(){
this.setState({
curTime: new Date().toLocaleString()
})
}.bind(this), 1000);
}
I would recommend to prefer using setTimeout instead of setInterval, indeed, the browser may be overhelmed by heavy processing and in that case you would probably prefer updating the clock less often instead of queuing several updates of the state.
With setTimeout it is also a bit easier to leverage the Page Visibility API to completely stop the clock when the page is hidden (see https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API).
export default class MyClock {
constructor(props) {
super(props);
this.state = {
currentTime: Date.now(),
};
}
updateCurrentTime() {
this.setState(state => ({
...state,
currentTime: Date.now(),
}));
this.timeoutId = setTimeout(this.updateCurrentTime.bind(this), 1000);
}
componentWillMount() {
this.updateCurrentTime();
document.addEventListener('visibilitychange', () => {
if(document.hidden) {
clearTimeout(this.timeoutId);
} else {
this.updateCurrentTime();
}
}, false);
}
componentWillUnmount() {
clearTimeout(this.timeoutId);
}
}
Full Code here:
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class KenTest extends Component {
componentDidMount(){
setInterval(() => (
this.setState(
{ curTime : new Date().toLocaleString()}
)
), 1000);
}
state = {curTime:new Date().toLocaleString()};
render() {
return (
<View>
<Text>{'\n'}{'\n'}{'\n'}The time is: {this.state.curTime}</Text>
</View>
);
}
}
Using hooks and moment-js:
setInterval(() => {
var date = moment().utcOffset("-03:00").format(" hh:mm:ss a");
setCurrentDate(date);
}, 1000);
Try this,
import * as React from 'react';
import { Text, View } from 'react-native';
export default function App() {
const [time, setTime] = React.useState();
React.useEffect(() => {
const timer = setInterval(() => {
setTime(new Date().toLocaleString());
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return (
<View>
<Text>{time}</Text>
</View>
);
}

Resources