Reputation:
I'm beginnner and I create my first app in React JS this is my code now:
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
function formatCountry(user) {
return user.country;
}
//this is my objet base of the user
const user = {
firstName: 'Simon',
lastName: 'willians',
country:'USA'};
const element = <h1>Hello, {formatName(user)}!</h1>;
const element2 = <h1>Country,{formatCountry(user)}!</h1>;
ReactDOM.render(element, document.getElementById('root'));
ReactDOM.render(element, document.getElementById('root'));
<div id="root"></div>
I create this app follow this tutorial of Facebook React JS
Okay I created a object with name user I return this object from formatName and formatCountry and the element of the object whatever exist in the object .
I try call country too in this sentence:
const element2 = <h1>Country,{formatCountry(user)}!</h1>;
any expert in React JS could tell me where is my error or where I mistakes?
Upvotes: 0
Views: 363
Reputation: 1
You have to use Babel. The tutorial you followed uses Babel to compile JavaScript under the hood.
1) Add Babel script to your head tag
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
2) Add type="text/babel" to the script tag where you wrote your code.
<script type="text/babel">
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Pereez',
};
const element = <h1>Hello, {formatName(user)}!</h1>;
ReactDOM.render(element,document.getElementById('root')
</script>
Upvotes: 0
Reputation: 17638
First of all you are trying to render same element, not element
and element2
. Secondly, if you render elements like that, only the last one is being rendered in the DOM. You need some wrapper element and inside this wrapper you will have your elements.
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
function formatCountry(user) {
return user.country;
}
const user = {
firstName: 'Simon',
lastName: 'willians',
country:'USA'};
const element2 = <h1>Country,{formatCountry(user)}!</h1>;
const element = (
<div>
<h1>Hello, {formatName(user)}!</h1>
{element2}
</div>
);
ReactDOM.render(element, document.getElementById('root'));
Maybe more elegantly:
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
function formatCountry(user) {
return user.country;
}
const user = {
firstName: 'Harper',
lastName: 'Perez',
country:'USA',
};
const userCountry = <h1>Country,{formatCountry(user)}!</h1>;
const userName = (
<h1>Hello, {formatName(user)}!</h1>
);
const element = (
<div>
{userName}
{userCountry}
</div>
)
ReactDOM.render(element, document.getElementById('root'));
Upvotes: 1