I am learning ReactJS, apologies if the question is basic.
I created a component:
import React, { Component } from 'react'; class title2 extends Component { constructor(props){ super(props); } render() { return ( <div className="shopping-list"> <h1>Shopping List for {this.props.name}</h1> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div> ); } } export default title2;
I want to render the component "title2" from my main component (App):
import React, { Component } from 'react'; import './App.css'; import title2 from './title2'; class App extends Component { constructor(props) { super(props); this.state = { name2: 'world', }; } render() { return ( <div className="App"> Hello {this.state.name2} {title2} </div> ); } } export default App;
This, in browser, displays "Hello world", however, it doesn't output anything from the "title2" component, and it doesn't result in error either. How can I solve this?
You should import it with the capital T:
import Title2 from './title2';
And then use it as a component:
render() {
return (
<div className="App">
Hello {this.state.name2}
<Title2 name="whatever name" />
</div>
);
}
React components should be named in UpperCamelCase. So change class title2 extends Component
to class Title2 extends Component
. Afterwards include the component like so:
render() {
return (
<div className="App">
Hello {this.state.name2}
<Title2 />
</div>
);
}
greetings
Change title2
to Title2
. From official React documentation:
When an element type starts with a lowercase letter, it refers to a built-in component like or and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.
We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.
See: https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
Also put Title2
inside a tag instead of curly braces: <Title2 />
Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX expression, Foo must be in scope.
See: https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.