Youtube channel !

Be sure to visit my youtube channel

Sunday, September 20, 2020

Starting with React


Here is how to create a simple application with the React front-end framework:


 

Setup the project:

sudo npm i -g create-react-app // install the dependencies
npx create-react-app my-react-app // create the initial application
npm start //start the live development server


App.js
import React from 'react';
import './App.css';
import Login from './loginComponent'; //default import
import {UsersList} from './usersList'; // specific import

const users = [ // using nested/presentational components
{ name: 'John', occupation: 'student', age: 23 },
{ name: 'Pete', occupation: 'teacher', age: 30 },
{ name: 'Anna', occupation: 'programmer', age: 35 }
];

const App = () => {
// double curly braces because of passing object and because of passing property
return (
<div className="App">
<Login user={{ name: "John", uid: 1000 }} />
<header className="App-header">
<UsersList users = {users} />
</header>
</div>
);
}

export default App;


usersList.js
import React from 'react';
import {UsersListItem} from './usersListItem'; // specific import

export const UsersList = ({ users }) => // getting especially users array from the passed array with props
( // with () we return automatically instead of writing {}
<>
{ users.map(user => <UsersListItem user={user} key={user.name} /> ) }
</>
);
// React will be used when we return react fragment


usersListItem.js
import React from 'react';
const sayMyName = (name) => {
alert(name);
}

export const UsersListItem = ({ user }) =>
(<div>
{user.name} -
{user.occupation} -
{user.age}
<button onClick={ ()=>sayMyName(user.name) }>Display name</button>
</div>
)


loginComponent.js
import React from 'react';
// show the import, conditionals and DOM element, also the export
// how to display props, destructurise in the passing parameters(props)

const Login = ({ user }) => {
let isAdmin = (user.uid) === 1000;
let logged_in = true;
// double conditional
return logged_in ? (
<>
hello mr.{user.name}
{ isAdmin ? `you are admin (conditional)` : null}
</>
)
: (<>please login</>)
}

export default Login;

No comments:

Subscribe To My Channel for updates

Integrating AI code helpers into Visual Studio Code

In this guide, we’ll walk through setting up a local AI-powered coding assistant within Visual Studio Code (VS Code). By leveraging tools s...