Repository navigation
2 jsx
If you don't have a code editor, install one (see the Tools wiki page for more info about editors).
Then open the project in the editor. You should see some folders and files:
-
node_modulesis where React and the other Javascript libraries are -
package.jsonhas some information about this project -
publicis where our project gets built to when we are ready to distribute it -
srcis the app code that we will edit.
.
├── README.md
├── node_modules
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
├── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ └── serviceWorker.js
└── yarn.lockSo, as the app suggests (have a look at the browser again), open the App.js file in your editor.
Just to demonstrate where the content is rendered, delete all the code between the header tags and write your name there instead. You should end up with this:
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
ben
</header>
</div>
);
}
export default App;Save the file and go back to the browser to see the change.
The App.js file is a component, a fundamental building block of React. It is an odd mix of Javascript and HTML-looking code. This mashup of code is known as JSX.
Read this article for a description of JSX
After reading that article, let's change the JSX in our App.js file to practise displaying data.
Inside the App() function, define a new variable with some string value (check the Javascript wiki page for more information about variables and strings) and give it a value. (This code snippet is just showing these few lines from the whole file.)
function App() {
const name = "me"
return (
...Now, replace the hard-coded name in the header tag to use the variable we just made. Remember from the article above, to use a variable in JSX we wrap the variable in curly brackets, e.g. {name}. Save and review in the browser.
import React from 'react';
import './App.css';
function App() {
const name = "me"
return (
<div className="App">
<header className="App-header">
{name}
</header>
</div>
);
}
export default App;Let's replace the single variable with an object, and show two object properties. Delete the name variable and create an object instead:
const person = {
name: 'Ben',
loc: 'the beach'
}Now in the header, delete the name variable and show the object's name and age values instead.
<h1>I'm {person.name}, find me at {person.loc}.</h1>Here's the full code.
import React from 'react';
import './App.css';
function App() {
const person = {
name: 'Ben',
loc: 'the beach'
}
return (
<div className="App">
<header className="App-header">
<h1>I'm {person.name}, find me at {person.loc}.</h1>
</header>
</div>
);
}
export default App;