Development Tips for React Developers

1. Updating an object with setState in React

> For example

this.state = {jasper:{name: 'jasper', age:28}}

1 > Object.assign

this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper)
jasper.name = 'someothername'
return { jasper }
})

2 > Spread Operator

this.setState(prevState => ({
jasper: { ...prevState.jasper,
name: 'something'
}
}))

2. Updating a nested object in React

> For example

this.state = {
"food":{
"sandwich":{
"capsicum":true,
"crackers":true,
"mayonnaise":true
},
"pizza":{
"jalapeno":true,
"extraCheese":false
}
}
}

> Spread Operator for nested object

this.setState(prevState => (
{
"food":{
"...prevState.food",
"pizza":{
"...prevState.food.pizza",
"extraCheese":true
}
}
})
)

3. Deploy App on a subdirectory

https://myapp.com/directory-name

1 > Set the base name

<Router basename={'/directory-name'}> 
<Route path='/' component {Home} />
...
</Router>

2 > Set the app homepage in package.json

"homepage" : "http://mywebsite.com/relativepath"

4. Render nested object

const fruits = {
"apple":{
"price":10,
"weight":2.5,
"color":"red"
},
"banana":{
"price":5,
"weight":1.2,
"color":"yellow"
}
}

> Object.keys() and use the key to map

render() {
Object.keys(fruits).map(function(fruit_name){
return(
<tr key={fruit_name}>
<tr>
<td>
<b> Template: {fruit_name} </b>
</td>
</tr>
{fruits[fruit_name].items.map(function(item){
return(
<tr key={item.id}>
<td>{item}</td>
</tr>
)
})}
</tr>
)
})
}

5. Simple nested Mapping

const mscList = classroomSummary.map((classRoom, ind) => (
classRoom.map(classData => (
<MSCItem classData={classData} />
))
))

6. Detect Route Change

> listen method in history property

constructor(props){
super(props);
this.props.history.listen((location, action) => {
// console.log('history changed')
this.routeChange();
})
}
// routeChange function
routeChange = () => {
const { BaseActions } = this.props
BaseActions.sideBar({expanded: false})
}

7. history push INSTEAD OF window.location

// CLIENT SIDE
history.push('/')
// SERVER SIDE
window.location('/')

8. Query String

> query string

resetBtn = () => {
const { history, schoolid,
selectedAgeValue, selectedDomain } = this.props;
history.push(`/reports/disadmin/${schoolid}
?age=${selectedAgeValue}&domain=${selectedDomain}`)
}
import queryString from 'query-string'const params = queryString.parse(window.location.search)const param_selectedAgeValue = params.ageconst param_selectedDomain = params.domainreturn state.set('param_selectedAgeValue', param_selectedAgeValue)

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.