ChartsJS |
Route |
Redux |
YAML |
Errors |
ESLint ESLint |
StyledComponents |
Index
- First install the global package:
npm install -g create-react-app
- Open project location then open CMD and type
create-react-app your-project-name
once it’s done, you can see created folder named 'your-project-name'
- Type npm start starting the Server browser will automatically open with localhost:3000
- open command line and type *i : install
npm i -S node-sass-chokidar
- Open package.json file and modify script block as per following
//...
"scripts": {
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
//...
- type this command and press enter
npm install --save npm-run-all
- Add SCSS file
App.scss
next to CSS file.
Create My_clock.js
//My_clock.js
import React, { Component } from 'react';
class Clock extends Component{
constructor(props){
super(props);
this.state = {
currentTime: new Date().toLocaleString()
}
this.updateTime();
}
/**updating time**/
updateTime(){
setInterval(() => {
this.setState({
currentTime : new Date().toLocaleString()
})
}, 1000)
}
/**./updating time**/
render(){
return(
<h1>{this.state.currentTime}</h1>
)
}
}
export default Clock;
//index.js
...
import Clock from './My_clock'; /*import Clock Class from My_clock.js */
...
ReactDOM.render(
<div>
<Clock /> /** display here **/
</div>
, document.getElementById('root'));
Props | State |
---|---|
Props are read-only | state changes can be asynchronous |
Props can not be modified | state can be modified using this.setState |
You should default to using stateless components. Since they use no state, it's very easy to tell when a component should be re-rendered, since they will display the same thing if their props do not change.
You should use stateful components when you need to use setState or when you need to use lifecycle hooks.
- Create new file 'My_stateless.js'
//My_stateless.js
import React from 'react'; /* not important import Component in Stateless Component */
function MyStatelessClock(props){
return <div>My Stateless Clock: {props.time}</div>
}
export default MyStatelessClock;
- Modify 'My_clock.js'
...
import MyStatelessClock from './My_stateless';
...
render(){
return(
...
<MyStatelessClock time={this.state.currentTime} /> /**<- add this code**/
...
)
}
...
Stateful components are always class components. stateful components have a state that gets initialized in the constructor.
Stateful | Stateless |
---|---|
constructor(props){... should use |
without constructor |
this.props.my_props_name | props.my_props_name * doesn't need to use this. |
- Modify 'My_clock.js'
...
import MyStatelessAnalog from './My_stateless_analog';
...
render(){
return(
<div>
<MyStatelessClock time={this.state.currentTime} />
<MyStatelessAnalog time={this.state.currentTime} />
</div>
)
}
...
- Create file for stateless functional 'My_stateless_analog'
import React from 'react';
function MyStatelessAnalog(props){
console.log(props.time);
let time = new Date(props.time);
let ClockHand = {
borderRadius: '50%',
borderStyle: 'solid',
width:200,
height:200,
}
let SecondPin = {
position: 'relative',
top:100,
left:100,
width:'45%',
height:1,
backgroundColor: 'green',
transform: 'rotate('+ ((time.getSeconds()/60)*360 - 90 ).toString() + 'deg)',
transformOrigin: '0% 0%',
}
let MinutePin = {
position: 'relative',
top:100,
left:100,
width:'40%',
height:2,
backgroundColor: 'blue',
transform: 'rotate('+ ((time.getMinutes()/60)*360 - 90 ).toString() + 'deg)',
transformOrigin: '0% 0%',
}
let HourPin = {
position: 'relative',
top:100,
left:100,
width:'20%',
height:4,
backgroundColor: 'orange',
transform: 'rotate('+ ((time.getHours()/60)*360 - 90 ).toString() + 'deg)',
transformOrigin: '0% 0%',
}
return (
<div style={ClockHand}>
<div style={SecondPin}></div>
<div style={MinutePin}></div>
<div style={HourPin}></div>
</div>
)
}
export default MyStatelessAnalog;
componentWillReceiveProps(nextProps){
console.log("Next Props: ", nextProps);
}
shouldComponentUpdate(newProps, newState){
console.log("should component update");
console.log("New Props", newProps);
console.log("New State", newState);
return true;
/* return false -> component updating in background but should not display on view */
}
componentWillUpdate(newProps, newState){
//just before update component
}
componentDidUpdate(oldProps, oldState){
//just after update component
console.log("component did update");
}
componentDidMount()(newProps, newState){
//just after render component
console.log("component did mount");
}
componentWillUnmount()(){
//just after render component
console.log("component will Unmount just before end or destroyed *trigger when component out of screen ");
}
NOTE: componentDidUpdate()
will not works if shouldComponentUpdate()
has returns false
import React, { Component } from 'react';
class MyEvent extends Component{
constructor(props){
super(props);
this.state = {
counter: 1
}
this.incrementHandler = this.incrementHandler.bind(this);
this.decrementHandler = this.decrementHandler.bind(this);
}
incrementHandler(){
this.setState(
{
counter: this.state.counter + 1
}
)
}
decrementHandler(){
this.setState(
{
counter: this.state.counter - 1
}
)
}
render(){
return(
<div>
<button onClick={this.incrementHandler}>Counter +</button>
<span className="counter"> {this.state.counter} </span>
<button onClick={this.decrementHandler}>Counter -</button>
</div>
)
}
}
export default MyEvent;
...
class TestMessage extends Component{
componentWillMount(){
document.title = "My Title"
}
render(){
return(
<b> test </b>
)
}
}
import React, { Component } from 'react';
class MyForm extends Component{
constructor(props){
super(props);
this.state={
username: "amoos jhon"
}
this.eventHandler = this.eventHandler.bind(this);
}
eventHandler(event){
this.setState({
username: event.target.value
})
}
render(){
return(
<div>
<input type="text" name="username" value={this.state.username} onChange={this.eventHandler} />
<span>{this.state.username}</span>
</div>
)
}
}
export default MyForm;
import React, { Component } from 'react';
class MyForm extends Component{
constructor(props){
super(props);
this.state={
username: '',
allusers: []
}
this.eventHandler = this.eventHandler.bind(this);
this.arrayHandler = this.arrayHandler.bind(this);
}
eventHandler(event){
this.setState({
username: event.target.value
})
}
arrayHandler(event){
let currentUser = this.state.allusers;
console.log(currentUser);
currentUser.push(this.state.username); //<-- without <span> element
//currentUser.push(<span className="any-class-name">{this.state.username}</span>); //<-- with <span> element
this.setState({
allusers: currentUser,
username: ''
})
console.log("Hello : " + this.state.allusers);
}
render(){
return(
<div>
<input type="text" name="username" value={this.state.username} onChange={this.eventHandler} />
<button onClick={this.arrayHandler}>Click to Store Username in Array</button>
<span>{this.state.allusers}</span>
</div>
)
}
}
export default MyForm;
...
constructor(props){
super(props);
...
devtype:{
MEANStack: false,
MERNStack: true,
LAMPStack: false
}
}
...
this.radioHandler = this.radioHandler.bind(this);
...
}
...
radioHandler(event){
console.log(event.target.value);
let devtype = this.devtype;
for (var key in devtype){
devtype[key] = false /* reset previous values */
}
devtype[event.target.value] = event.target.checked
// this.setState({ devtype: event.target.value })
this.setState({
devtype: devtype
})
}
render(){
return(
<div>
...
<h4>Developer Category</h4>
<label>
MEAN Stack <input type="radio" name="devcat" value="MEANStack" checked={this.state.devtype['MEANStack']} onChange={this.radioHandler} />
</label>
<br/>
<label>
MERN Stack <input type="radio" name="devcat" value="MERNStack" checked={this.state.devtype['MERNStack']} onChange={this.radioHandler} />
</label>
<br/>
<label>
LAMP Stack <input type="radio" name="devcat" value="LAMPStack" checked={this.state.devtype['LAMPStack']} onChange={this.radioHandler} />
</label>
</div>
)
}
}
export default MyForm;
...
constructor(props){
super(props);
this.state={
...
techtype: {
mongodb: false,
react: false,
express: true,
node: false
}
}
...
this.techHandler = this.techHandler.bind(this);
}
...
techHandler(event){
let tech = this.state.techtype;
tech[event.target.value] = event.target.checked;
this.setState({
techtype: tech
})
}
render(){
return(
<div>
...
<h4>Technogies</h4>
<label>
MongoDB <input type="checkbox" name="tech" value="mongodb" checked={this.state.techtype['mongodb']} onChange={this.techHandler} />
</label>
<br/>
<label>
Express <input type="checkbox" name="tech" value="express" checked={this.state.techtype['express']} onChange={this.techHandler} />
</label>
<br/>
<label>
ReactJS <input type="checkbox" name="tech" value="react" checked={this.state.techtype['react']} onChange={this.techHandler} />
</label>
<label>
NodeJS <input type="checkbox" name="tech" value="node" checked={this.state.techtype['node']} onChange={this.techHandler} />
</label>
</div>
)
}
}
export default MyForm;
...
constructor(props){
super(props);
this.state={
...
selectValue: ''
}
...
this.selectHandler = this.selectHandler.bind(this);
}
selectHandler(event){
this.setState({
selectValue: event.target.value
})
}
render(){
return(
<div>
...
<h4>Select Favourate Language</h4>
<select value={this.state.selectValue} onChange={this.selectHandler}>
<option>Ruby</option>
<option>PHP</option>
<option>ASP .NET</option>
</select>
{this.state.selectValue}
</div>
)
}
}
export default MyForm;
import React, { Component } from 'react';
class MyForm extends Component{
constructor(props){
super(props);
this.state={
useremail: ''
}
this.emailHandler = this.emailHandler.bind(this);
}
emailHandler(){
console.log(this.refs.userEmail.value); //<-- Ref NOT recommended is Uncontrolled
}
render(){
return(
<div>
<input type="email" ref="userEmail" />
<button onClick={this.emailHandler}>Submit</button>
</div>
)
}
}
export default MyForm;
Open command line and type npm install --save react-router-dom
- Create
src/Routes.js
file
import React from 'react';
import { BrowserRouter as Router, Route, Link} from 'react-router-dom';
import App from './App';
import AboutPage from './layout/about'; // <-- about.js imported form '/about' route
const MyRoutes = () =>(
<Router>
<div>
<Route exact path='/' component={App} /> // <-- 'exact' using to avoid conflict
<Route path='/about' component={AboutPage} />
</div>
</Router>
)
export default MyRoutes;
- Create inner page
src/layout/about.js
import React, { Component } from 'react';
class AboutPage extends Component{
render(){
return(
<div>
<h2>About Page</h2>
</div>
)
}
}
export default AboutPage;
- Modify
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import MyRoutes from './Routes.js'; //<-- Routes file
ReactDOM.render(
<div>
<MyRoutes /> //<-- Routes.js component will load here
</div>
, document.getElementById('root'));
//registerServiceWorker();
- Create '.layout/navbar.js' file
import React from 'react';
import { Link } from 'react-router-dom'; //<-- Just import 'Link' only as we need
const Navbar = () => (
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='about'>About</Link></li>
</ul>
)
export default Navbar;
- Modify
Routes.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './App';
import AboutPage from './layout/about';
import Navbar from './layout/navbar';
const MyRoutes = () =>(
<Router>
<div>
<Navbar /> //<-- Added navigation here
<hr />
<Route exact path='/' component={App} />
<Route path='/about' component={AboutPage} />
</div>
</Router>
)
export default MyRoutes;
- Create
layout/login.js
import React, { Component } from 'react';
class LoginPage extends Component{
constructor(props){
super(props)
this.state={
pass:''
}
this.eventHandler = this.eventHandler.bind(this);
}
loginHandler(event){
this.setState({
pass: event.target.value
})
var passCheck = this.state.pass; //<-- storing updated password in var
if(passCheck === "mypass"){
this.props.history.push('/'); //<-- .push('your-next-url')
}else{
alert(passCheck+ " please try agian!");
}
}
eventHandler(event){
this.setState({
pass: event.target.value
})
}
render(){
return(
<div>
<h2>Login Page</h2>
<input type="text" name="pass" value={this.state.pass} onChange={this.eventHandler} />
<button onClick={this.loginHandler.bind(this)}>Login</button>
<p>Correct password: 'mypass'</p>
</div>
)
}
}
export default LoginPage;
- Modify
Route.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './App';
import AboutPage from './layout/about';
import LoginPage from './layout/login'; //<-- Login imported here
import Navbar from './layout/navbar';
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory(); //<-- creating History
const MyRoutes = () =>(
<Router histor={customHistory}> //<-- history called on Router
<div>
<Navbar />
<hr />
<Route exact path='/' component={App} />
<Route path='/about' component={AboutPage} />
<Route path='/login' component={LoginPage} /> //<-- Added Login Route here
</div>
</Router>
)
export default MyRoutes;
- Add login link in
navbar.js
import React from 'react';
import { Link } from 'react-router-dom';
const Navbar = () => (
<ul>
...
<li><Link to='login'>Login</Link></li>
</ul>
)
export default Navbar;
Warning: ignores the history prop. To use a custom history, use import { Router }
instead of import { BrowserRouter as Router }
.
import React from 'react';
import { Router, Route } from 'react-router-dom';
import App from './App';
import AboutPage from './layout/about';
import LoginPage from './layout/login';
import Navbar from './layout/navbar';
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
const MyRoutes = () =>(
<Router history={customHistory}>
<div>
<Navbar />
<hr />
<Route exact path='/' component={App} />
<Route path='/about/:userid' component={AboutPage} /> {/*<-- userid passed in url */ }
<Route path='/login' component={LoginPage} />
</div>
</Router>
)
export default MyRoutes;
//About.js
import React, { Component } from 'react';
class AboutPage extends Component{
render(){
/*User records in JSON format*/
let users = {
157:{
name: "Amoos",
cell: "124545"
},
158:{
name: "Ebad",
cell: "457587"
},
159:{
name: "Hussain",
cell: "59859"
}
}
let requiredUser = users[this.props.match.params.userid] //<-- sorting params to 'requiredUser' varible
return(
<div>
<h2>About Page</h2>
User ID: {this.props.match.params.userid} *by normal syntax
<br/>
User Name: {requiredUser.name} *by sorting into variable
<br/>
User Cell: {requiredUser.cell} *by sorting into variable
</div>
)
}
}
export default AboutPage;
//Login.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class LoginPage extends Component{
constructor(props){
super(props)
this.state={
pass:''
}
this.eventHandler = this.eventHandler.bind(this);
}
loginHandler(event){
this.setState({
pass: event.target.value
})
var passCheck = this.state.pass; //<-- storing updated password in var
if(passCheck === "mypass"){
this.props.history.push('/about/157'); //<-- .push('your-next-url')
}else{
alert(passCheck+ " please try agian!");
}
}
eventHandler(event){
this.setState({
pass: event.target.value
})
}
render(){
return(
<div>
<h2>Login Page</h2>
<input type="text" name="pass" value={this.state.pass} onChange={this.eventHandler} />
<button onClick={this.loginHandler.bind(this)}>Login</button>
<p>Correct password: 'mypass'</p>
<ul>
<li><Link to='/about/158'>About with 158 UserID</Link></li>
<li><Link to='/about/159'>About with 159 UserID</Link></li>
</ul>
</div>
)
}
}
export default LoginPage;
- Create
layout/notfounde.js
import React, { Component } from 'react';
class NotFoundPage extends Component{
render(){
return(
<div>
<h2>NOT FOUND</h2>
</div>
)
}
}
export default NotFoundPage;
- Modify
Routes.js
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom'; //<-- add <Switch> here
import App from './App';
import AboutPage from './layout/about';
import LoginPage from './layout/login';
import NotFoundPage from './layout/notfound'; //<-- Not found page
import Navbar from './layout/navbar';
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
const MyRoutes = () =>(
<Router history={customHistory}>
<div>
<Navbar />
<hr />
<Switch>
<Route exact path='/' component={App} />
<Route path='/about/:userid' component={AboutPage} /> {/*<-- userid passed in url */ }
<Route path='/login' component={LoginPage} />
<Route component={NotFoundPage} /> {/* not found url */}
</Switch>
</div>
</Router>
)
export default MyRoutes;
Note: Wrap all Routes inside of a Switch
only the first match will ever be rendered.
Dont forget to use Switch
NotFound component no matter what path we’re on, because the Route has no path, and if it has no path, it will always be rendered...
...
import { Router, Route, Switch, Redirect } from 'react-router-dom';
...
const MyRoutes = () =>(
<Router history={customHistory}>
<div>
<Navbar />
<hr />
<Switch>
...
<Redirect from="/old-url" to="/new-url" />
<Redirect from="/about-us" to="/about" />
<Route component={NotFoundPage} />
</Switch>
</div>
</Router>
)
export default MyRoutes;
Add ClassName module
yarn add classnames --save
OR npm install classnames --save
Code this where you want.
var btn = getClassNames() {
return classNames({
'is-active': this.state.clicked,
'is-inactive': !this.state.clicked
});
},
render () {
return <button className={this.getClassNames()} onClick={this.setState({clicked: !this.state.clicked})>
}
npm install react-chartjs-2 chart.js --save
Usage:
import { defaults } from 'react-chartjs-2';
defaults.global.animation = false; // Disable animating charts by default.
<Bar
data={data}
width={100}
height={50}
options={{
maintainAspectRatio: false
}}
/>
- Add follwing package on
package.json
file
// package.json
{
name:"..."
...
"dependencies": {
...
"react-redux": "^5.0.6",
"react-router-redux": "^5.0.0-alpha.9",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0"
...
},
...
}
- Open command line type
npm install
For Only react-redux npm install --save react-redux
Logger for Redux. ... Log only in development; Log everything except actions with certain type ... import { createLogger } from 'redux-logger'
An action creator that returns a function to perform asynchronous dispatch.
_One Component
App Component /
\_Aonther Component
- Create spearte file for history
History.js
//History.js
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
export default customHistory;
- Import into
Routes.js
// Routes.js
...
import history from "./History";
...
- Create following file/folder for redux functions
//store/index.js
import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk'; //<-- for action dispatch
import allReducers from './reducer';
const store = createStore(
allReducers,
{},
applyMiddleware(thunk)
)
export default store;
//store/reducer/index.js
import my_reducer from './reducer';
import { combineReducers } from 'redux';
export default combineReducers({
rootReducer: my_reducer
})
//store/reducer/my_reducer.js
const INITIAL_STATE = {
userName: 'Alex Josh'
}
//static data for now
export default (state = INITIAL_STATE, action)=>{
switch(action.type){
default:
return state;
}
}
- Modify
index.js
Note After import react-redux and store make parent for .
...
import {Provider} from "react-redux"; //<-- Added
import store from './store'; //<-- Added
ReactDOM.render(
<div>
<Provider store={store}> //<-- Added
<MyRoutes />
</Provider> //<-- Added
</div>
, document.getElementById('root'));
- Access and diplay data from Redux store
Code.
{this.props.userName}
//About.js
import React, { Component } from 'react';
import { connect } from "react-redux"; //<-- Added
class AboutPage extends Component{
render(){
...
return(
<div>
<h2>About Page {this.props.userName} </h2>
...
</div>
)
}
}
/**redux**/
function mapStateToProps(state){
return({
userName: state.rootReducer.userName
})
}
function mapDispatchToProps(dispatch){
return({ })
}
/**./redux**/
export default connect(mapStateToProps, mapDispatchToProps)(AboutPage);
- Modify
about.js
//about.js
import React, { Component } from 'react';
import { connect } from "react-redux";
import { changeState } from '../store/action/action'; //<-- added
class AboutPage extends Component{
_changeState(){
this.props.changeStateToReducer()
}
render(){
...
return(
<div>
<h2>About Page {this.props.userName} </h2>
<button onClick={this._changeState.bind(this)}>Change Redux State</button>
...
</div>
)
}
}
/**redux**/
function mapStateToProps(state){
return({
userName: state.rootReducer.userName
})
}
function mapDispatchToProps(dispatch){
return({
changeStateToReducer: ()=>{ /* custom name */
dispatch(changeState()); //<-- changeState from <action.js> || usage: this.props.changeStateToReducer()
}
})
}
/**./redux**/
export default connect(mapStateToProps, mapDispatchToProps)(AboutPage);
- Modify
my_reducer.js
//reducer/my_reducer.js
const INITIAL_STATE = {
userName: 'Alex Josh',
rollNumber: '157'
}
export default (states = INITIAL_STATE, action)=>{
switch(action.type){
case 'CHANGEUSERNAME':
return ({
...states,
userName: action.payload
})
default:
return states;
}
}
- Create
action/action.js
file
export function changeState(){
return dispatch =>{
//console.log("from action..");
dispatch({type:'CHANGEUSERNAME', payload: 'New Name'}) /*payload = new or updated state data*/
}
}
Create new file for fetch API data
//data_fetch.js
import React, { Component } from 'react';
import yaml from 'js-yaml';
import $ from 'jquery';
class DataFetchPage extends Component{
constructor(props){
super(props)
this.state={
demo_var: "dummy text"
}
}
render(){
$.get( 'https://raw.githubusercontent.com/nodeca/js-yaml/2d1fbed8f3a76ff93cccb9a8a418b4c4a482d3d9/examples/sample_document.yml', function( data2 ) {
var data = yaml.load( data2 );
console.log( data.timestamp ); //
});
return(
<div>
{this.state.demo_var}
</div>
)
}
}
export default DataFetchPage;
- Modify Routes.js
//Routes.js
// ...
import DataFetchPage from './layout/data_fetch';
// ...
<Switch>
//...
<Route path='/data_fetch' component={DataFetchPage} />
//...
</Switch>
//...
- Modify Navbar.js
//Navbar.js
// ...
<li><Link to='/data_fetch'>Data Fetch (API)</Link></li>
// ...
NOTE: see result in console.
import React, { Component } from 'react';
import yaml from 'js-yaml';
import $ from 'jquery';
import jdata from '../_data/data.json';
class DataFetchPage extends Component{
constructor(props){
super(props)
this.state={
demo_var: "dummy text",
}
}
componentDidMount() {
console.log("Data loaded :" +jdata[1].title);
}
render(){
const listJsonData = jdata.map(
(d) =>
<div key={d.id}>
<span>{d.id} - </span>
<span>{d.title}</span>
</div>
);
return(
<div>
{listJsonData}
{this.state.demo_var}
</div>
)
}
}
export default DataFetchPage;
-
yarn add react-dates
-
An example for date range component file code
// DatePicker.jsx
/*eslint-disable */
import React, { Component } from 'react'
import {SingleDatePicker} from 'react-dates';
import 'react-dates/initialize';
class DatePicker extends Component {
constructor(props) {
super(props);
this.state ={
date: null,
focused: null
}
}
render() {
return (<div>
Date Picker
<SingleDatePicker
// showClearDate={true}
customInputIcon={
<svg className="icon icon-small">
</svg>
}
inputIconPosition="after"
small={true}
block={false}
numberOfMonths={1}
date={this.state.date}
onDateChange={date => this.handleDateChange(date)}
focused={this.state.focused}
onFocusChange={({ focused }) =>
this.setState({ focused })
}
openDirection="up"
hideKeyboardShortcutsPanel={true}
/>
</div>)
}
}
export default DatePicker
- Add component where you want.
// ...
import DatePicker from '../DatePicker';
// ...
render() {
return (<CalenderBarWrapper>
<DatePicker />
// ...
Add below code at the beginning of your application, It worked for me
import 'react-dates/initialize';
- configuration.module has an unknown property 'loaders'. These properties are valid:
- webpack config problem... there was no css loader in the config.
Still not working... ???
yarn add css-loader --save-dev
and add following rules in webpack config.
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
// ...
Open package.json
, added following rules under rules line:
"rules": {
"linebreak-style": 0,
"global-require": 0,
...
for VScode users: click the option at the bottom-right of the window and set it to LF
from CRLF
errors will fixed for me
// RIGHT
<button onClick={() => {}} className="foo" />
<div className="foo" onClick={() => {}} role="button" />
<input type="text" onClick={() => {}} />
//WRONG
<div onClick={() => {}} />
<div
role="button"
tabIndex={0} />
// WRONG
<span>
My Text
</span>
// Right * Strings must use singlequote quotes
<span>
{'My Text'}
</span>
npm install --save styled-components.
npm install style-loader --save-dev
body:not(&) { overflow: hidden; }
yarn init
yarn install
rimraf is the UNIX command rm -rf for node, need to install it with
npm install rimraf -g.
'cross-env' is not recognized as an internal or external command,
install cross-env with npm
npm install cross-env
import React from "react";
import { Link } from "react-router-dom";
const HomePage = () => {
<div>
<h1>Home Page</h1>
<Link to="/login">Login</Link>
</div>
}
export default HomePage;
Note: replace curly {} with rounded brackets ()
...
const HomePage = () => (
<div>
<h1>Home Page</h1>
<Link to="/login">Login</Link>
</div>
)
...
Note: make sure you have added params in routes.js
import React from 'react';
import { Router, Route } from 'react-router-dom';
import App from './App';
import AboutPage from './layout/about';
...
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
const MyRoutes = () =>(
<Router history={customHistory}>
<div>
...
<Route path='/about/:userid' component={AboutPage} />
</div>
</Router>
)
export default MyRoutes;
...
this.state={
anotherVar: '',
anyVaribleName: '' //<-- Incorrect syntax .push()
anyVaribleName: [] //<-- Correct syntax .push()
}
...
this.myStateVarible;
DONT forget to use .state before your state varible this.state.myStateVarible;
open commandline and install jQuery
npm i jquery --save
import jquery file where you need
// file_name.js
// ...
import $ from 'jquery';
// ...
UPDATE: Installing a previous version of Webpack solved the issue.
npm install webpack@2.2.0 --save-dev
Solution: Run npm upgrade
After running npm install -D extract-text-webpack-plugin@next
solved this issue for me.
-
component should start with CAPITAL 'C' Component
-
Don't use
=
in setState, Use:
instead of '=' -
Missing
return(<div>...</div>)
in renderrender(){ (<div>...</div> )}
-
'Component' is not defined no-undef
make sure{ Component }
added hereimport React, { Component } from 'react';
-
Use
this.state={...
instead ofstate:{...
// Wrong
...
super(props);
state : {
counter: 1
}
...
// Wrong 2.0 : forget to use 'this.state'
constructor(props){
super(props)
demovar: "dummy text"
}
// Right
...
super(props);
this.state = {
counter: 1
}
...
Note Also make sure event handler binded in constructor like this -> this.myEventHandler = this.myEventHandler.bind(this);
//WRONG
radioHandler(){
this.setState({
devtype: this.setState.target.value
})
console.log(this.state.devtype);
}
//RIGTH
radioHandler(event){
console.log(event.target.value);
let devtype = this.devtype;
for (var key in devtype){
devtype[key] = false /* reset previous values */
}
devtype[event.target.value] = event.target.checked;
}
- Don't use
Return(...)
inside Routing Arrow function in ReactJS
//WRONG
const Navbar = () =>{ //<--DONT use curly brackets
return( //<--DONT add return() here
)
}
Note: use round brackets const Navbar = () => (...)
instead of curly brackets const Navbar = () => {...}
..
//RIGHT
const Navbar = () =>(
<ul>
<li><Link to="your-link">Your Text</Link></li>
</ul>
)
//WRONG
export function changeState(){
console.log("from action..");
}
//RIGHT
export function changeState(){
return dispatch =>{
console.log("from action..");
}
}
// Wrong
class D3Map extends React(){
// ...
}
// Right
class D3Map extends Component{
// ...
}
// WRONG
export default from './Chartsjs'
// Right
export { default } from './Chartsjs'
yarn add babel-plugin-inline-react-svg --save-dev
yarn add babel-plugin-transform-replace-object-assign
yarn add babel-preset-airbnb --save-dev
yarn add babel-plugin-add-module-exports
enable blockBindings in your .eslintrc file:
// ...
"ecmaFeatures": {
"blockBindings": true
},
// ...
https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en
It's naming convention which is common also in other other languages. Mainly because of actions is being refereed from multiple modules, Easy readability in code, Actions are important focus as they are meant to change the state of the ReactUI.
const ActionsExample = {
LOAD_POSTS_REQUEST: 'LOAD_POSTS_REQUEST',
LOAD_POSTS_FAILURE: 'LOAD_POSTS_FAILURE',
LOAD_POSTS_SUCCESS: 'LOAD_POSTS_SUCCESS',
};
Functional Component
- Used for presenting static data
- Can't handle fetching data
- Easy to write
const Header = () => {
return < Text>Hello Amoos!</Text>
}
Class Component
- Used for dynamic sources of data
- Handles any data that might change (fetching data, user events, etc)
- Knows when it gets erendered to the
- device (useful for data fetching)
- More code to write
class Header extends Component {
render() {
return < Text>Hello Amoos!</Text>
}
}
style names according base on condition
<div className={'myStaticClass ' + ( condition ? " myClass" : " anotherClass")'}>
//...content
</div>
with css modules.
//...
return (
<div className={`myStaticClass ${styles.moduleClass} ${(condition ? ' myClass' : ' anotherClass')`}>
//...content
</div>
)
REACT_APP_DOMAIN=something.com |OR| localhost
REACT_APP_RUN_AS_LOCALHOST=true
import { useEffect } from "react";
import Setting from "./Setting";
const ConsoleLogSetting = ( ) => {
useEffect( ()=> {
if(!Setting.consoleLog) {
console.log = function() {}
console.warn = function() {}
console.error = function() {}
}
}, [])
}
export default ConsoleLogSetting;
import ConsoleLogSetting from "./ConsoleLog";
const domain = process.env.REACT_APP_DOMAIN;
const isLocal = process.env.REACT_APP_RUN_AS_LOCALHOST;
const Setting = {
somethingAlert: false,
consoleLog: true,
localhost: isLocal,
domain: !isLocal ? '.'+domain : domain,
}
export default Setting;
export {
ConsoleLogSetting
}
//..
<ConsoleLogSetting />
{ Setting.localhost ? "is localhost" : "is domain" }
//..