Reputation: 1078
I wrote a function. I used only simple letters for the name of that function. I didn't get any output and error. I highlighted this function.
Lesson3.js
import React from 'react'
function formattedDate(props){
return(
<div>This is {props.date.toLocaleTimeString()}</div>
);
}
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><formattedDate date={this.state.date}/></h1></div>
);
}
}
export default Clock
So I checked my entire code. But I didn't catch any bugs. After I changed the function name to the uppercase name, I got the output. Please explain the reason for that.
import React from 'react'
function FormattedDate(props){
return(
<div>This is {props.date.toLocaleTimeString()}</div>
);
}
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><FormattedDate date={this.state.date}/></h1></div>
);
}
}
export default Clock
I imported Lesson3.js to App.js. There's no bug in my code except that error I mentioned above.
App.js
import React from 'react';
import './App.css';
import Clock from './Components/lesson3'
function App() {
return (
<div className="App">
<p>
<Clock/>
</p>
</div>
);
}
export default App;
Upvotes: 0
Views: 2313
Reputation: 387
React treats components starting with lowercase letters as DOM tags.
For example, <div />
represents an HTML div tag,
So in :
<formattedDate .../>
React treat as DOM tag, Obviously which it is notOn otherhand <UpperCase />
represents a component and requires it to be in its scope
<FormattedDate />
represents a component and requires FormattedDate to be in scope.If you want to learn more about component you can read more at React Offical docs for component and props
Upvotes: 1
Reputation: 4289
It's a naming convention to use capitalized variable/function names for components, to distinguish them from regular/helper/etc functions.
function Button() { return <button>Test</button> }
function sortNumbers(array) { return ... }
Upvotes: 2
Reputation: 1636
Here, you have tried to use FormattedDate
as a component
. Not as an ordinary function.
All React component names must start with a capital letter. If you start a component name with a lowercase letter, it will be treated as a built-in element like a <div>
or a <span>
. This is because of the way JSX works.
You can find more information here
Upvotes: 1