Initializing a React App
Desktop > cd folder_name
Desktop/folder_name > npm init react-app .
Desktop/folder_name > npm start
Ways to write Components
// Ways to write components
// Normal JavaScript Function
function Nav(props){
return (
<ul>
<li>{props.first}</li>
</ul>
)
}
// Component as Function expression
const Nav = function(props){
return (
<ul>
<li>{props.first}</li>
</ul>
)
}
// Render the Nav component
<Nav first = "Home"/>
// Component as Arrow Function
const Nav = (props) => {
return (
<ul>
<li>{props.first}</li>
</ul>
)
}
// Parantheses optional if only single parameter
const Nav = props => {
return (
<ul>
<li>{props.first}</li>
</ul>
)
}
// Without any parameters
const Nav = () => {
return (
<ul>
<li>{props.first}</li>
</ul>
)
}
// Implicit return from the arrow function
// Works only with one-liner compnents
const Nav = () => <ui><li>Home</li></ul>
Props
Ternary Operator
// Normal way of writing if...else condition
name = "Bob"
if (name == "Bob"){
console.log("Hello Bob")
} else {
console.log("Hello Friend")
}
// Using ternary Operator to write the same
name = "Bob"
name == "Bob" ? console.log("Hello Bob") : console.log("Hello Friend")
// if condition ? if true do this : if false do this
// comparison ? true : false
Event Handling in React
Using inline anonymous ES5 functions
<button onClick={function() {console.log('first example')}}>
An inline anonymous ES5 function event handler
</button>
Using arrow functions
<button onClick={() => console.log('second example)}>
An inline anonymous ES^ function event handler
</button>