I'm new to coding and have spent a long time trying to make this work but I am stuck. I know this is a very basic question and if it is answered elsewhere, I have failed to find the right questions to search to find that answer.
This is from the react tutorial -- it is the automatic timer that self-updates every 1000ms. I would like to be able to pass a prop
into the <Clock />
function call to specify the interval I want that specific object instance to use like so: <Clock interval=2000 />
Here is the code they provided:
function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}
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>
<FormattedDate date={this.state.date} />
</div>
);
}
}
function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Here is what I have tried:
- Setting the state to have
timer: 5000
- passing it in as a
const
to the function call - then updating the state in
componentDidMount
However, this does not work because I am trying to use a prop
to update state
. What am I supposed to do instead?
Unsuccessful code: (just the bits I've tried)
this.state = {
date: new Date(),
interval: 5000,
};
componentDidMount(props){
() => this.tick(),
props.timer
);
}
const timer = {
interval: 5000,
}
ReactDOM.render()
<Clock interval={timer.interval}/>,
document.getElementById('root')
);
CodePudding user response:
if you want to pass the interval as a prop you can do it like this:
<Clock interval="1000"/>
and access it like this:
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
this.props.interval
);
}
You have to use this.props
to have access to your props in the class components.