Index.js
Our app lives in the /src folder index.js being is the main entry point for our app.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
Application
Every React application has at least one component: the root component, named App. The App component controls the view through JSX template, with return().
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>My React App</h2>
</div>
</div>
);
}
}
export default App;
Products.js
Note the naming convension for the component file. The first letter must be uppercase.
import React, { Component } from 'react';
class Products extends Component {
render() {
return (
<h2>Products</h2>
);
}
}
export default Products;
Root Element
Components must return a single root element. This code will throw an error.
class Products extends Component {
render() {
return (
<h2>Products</h2>
<h2>Courses</h2> // error
);
}
}
Import
Import and add Product to the template. We can also render Products many times.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Products from './Products'; // import component
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" />
<h2>My React App</h2>
<Products /> // render products
<Products />
<Products />
</div>
</div>
);
}
}
export default App;
Embeded Javascript
We can embed Javascript template string into JSX using wrapping it in curly braces. Key should be unique strings (most often you would use ids).
import React, { Component } from 'react';
class Products extends Component {
render() {
// array products
const products = ["Learning React", "Pro React"];
// ES6 arrow function (product) =>
const listProducts = products.map((product) =>
<li key={product.toString()}>{product}</li>
);
return (
<div>
<ul>{listProducts}</ul> // render products
</div>
);
}
}
export default Products;
Last update: 382 days ago