// importing cssimport"./App.css"// React componentconstApp=()=>{// class attribute as className and inline stylesreturn(<><h1
className="main"// inline css
style={{fontSize:24,margin:"0 auto",textAlign:"center"}}>// javascript in jsx (conditional example) Hello World I am{" "}{name ==="Damon"?"(admin)":"(user)"}</h1>// Close every element<img src="/image/jpg"/></>)}exportdefault App
// Render
ReactDOM.render(<App />, document.getElementById("root"))
Props
functionApp(){return<User name="John Doe"/>}functionUser(props){return<h1>Hello,{props.name}</h1>}// Children PropsfunctionApp(){return(<User><h1>Hello, John Doe!</h1></User>)}functionUser({ children }){return children
}
constclickHandler=e=>alert(e.target)functionApp(){return(<><h1>Welcome to my app</h1><button onClick={clickHandler}>Say Hi</button></>)}// inlinefunctionApp(){return(<><h1>Welcome to my app</h1><button onClick={()=>alert("Hello World")}>Say Hi</button></>)}
PropTypes
import PropTypes from"prop-types"classGreetingextendsReact.Component{render(){const children =this.props.children
return(<div><h1>
Hello,{this.props.name}{this.props.lastName}.</h1>{children}</div>)}}
Greeting.propTypes ={name: PropTypes.string,children: PropTypes.element.isRequired,}// Specifies the default values for props:
Greeting.defaultProps ={lastName:"Stranger",}
import React,{ useState, useEffect }from"react"functionExample(){const[count, setCount]=useState(0)// Similar to componentDidMount and componentDidUpdate:useEffect(()=>{// Update the document title using the browser API
document.title =`You clicked ${count} times`// clean up function runs before the component is unmountedreturn()=>{
console.log("Cleaned up")}},[count])// Will run each time 'count' state change.// If empty array, it will then only run once on initial renderreturn(<div><p>You clicked {count} times</p><button onClick={()=>setCount(count +1)}>Click me</button></div>)}
useRef
import{ useRef, useEffect }from"react"// useRef allows us to get direct access to a JSX element.(DOM element)// Does not trigger a re-renderconstUseRefBasics=()=>{const refContainer =useRef(null)consthandleSubmit=e=>{
e.preventDefault()
console.log(refContainer.current.value)}useEffect(()=>{
refContainer.current.focus()},[])return(<div><form className="form" onSubmit={handleSubmit}><div><input ref={refContainer} type="text"/><button type="submit">Submit</button></div></form></div>)}
useContext
import{ createContext, useContext }from"react"// useContext is a hook that returns the data for the given contextconst ThemeContext =createContext("light")functionApp(){return(<ThemeContext.Provider value="light"><Component /></ThemeContext.Provider>)}functionComponent(){const theme =useContext(ThemeContext)// returns 'light'return(<div><p>The current theme is:{theme}</p></div>)}
useReducer
import{ useReducer }from"react"// useReducer may be used as an alternative to useState.// It’s ideal for complex state logic// it uses the Redux patternfunctionApp(){const[count, dispatch]=useReducer((state, action)=>{switch(action){case"increment":return state +1case"decrement":return state -1default:thrownewError()}},0)return(<div><p>{count}</p><button onClick={()=>dispatch("increment")}>+</button><button onClick={()=>dispatch("decrement")}>-</button></div>)}
Router
Part I
import{ BrowserRouter as Router, Route, Switch }from"react-router-dom"exportdefaultfunctionApp(){return(<Router><Navbar />// visible on every page<Switch><Route exact path="/" render={()=><Home />}/><Route path="/about" component={About}/>// 404 page not found<Route path="*" component={NotFound}/></Switch></Router>)}functionNavbar(){return(<nav><Link to="/">Home</Link><Link to="/about">About</Link></nav>)}
Part II
import{
BrowserRouter as Router,
Switch,
Route,
Redirect,
useHistory,
useParams
}from"react-router-dom";// RedirectconstProfile=({isLoggedIn})=>{if(!isLoggedIn){return<Redirect to="/sign-up"/>}else{return<ProfileInfo />}}// useParams// "/users/:userName"exportdefaultconstUserProfile(){const{ userName }=useParams()return(<h1> Welcome {userName}!</h1>)}// useHistoryexportdefaultfunctionFooter(){const history =useHistory();return(<footer><button onClick={()=> history.goBack()}>
Back
</button><button onClick={()=> history.goForward()}>
Forward
</button><button onClick={()=> history.push('/about')}>
About
</button></footer>)}
A personal blog by Volkan Uyarer. Developer, Lifelong Learner, Tech Enthusiast.