Basic React Things that most of us don't know yet

Kunal Mehta
5 min readApr 29, 2019

--

I came up with a small list of things I wish I knew when I started to learn ‘React’ that save a lot of time and efforts now and want to share them with you. This article does not explain core concepts of React and won’t give you a crash course of writing views in it but rather some tips that would make the development experience more pleasant and easier.

1. React Fragments: It is very common that your components in React would need several HTML elements to be returned together. In our <Table/> we want to use <Columns/> which returning nothing more than a couple of <td>s.

class Table extends React.Component {
render() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
}

Note, that we can’t just return those as React will throw an error - Adjacent JSX elements must be wrapped in an enclosing tag. So we have an option of providing a single parent container, which can be <div> in this case.

class Columns extends React.Component {
render() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
}

Two components mentioned above are totally valid and work without producing any errors, but you may frequently stumble on the unpleasant fact that wrapping everything into a <div> will often break the layout or would create a necessity for redundant CSS. React offers a really neat workaround with its native Fragment syntax. All the layout problems can be mitigated by using them

class Columns extends React.Component {
render() {
return (
<React.Fragment>
<td>Hello</td>
<td>World</td>
</React.Fragment>
);
}
}

Moreover, you can also use shorter syntax and declare a fragment in the following way. It’s highly likely that it’s supported by up to date versions of tools you are using with react, but in case it’s not - <React.Fragment> is always an option!

<>
<td>Hello</td>
<td>World</td>
</>

2. I hate bindings and now you can hate them too :)

Usually, you will have something like this when you have a controlled component:

class LearnReact extends React.Component{
constructor( props ){
super( props );
this.onClick= this.onClick.bind(this);
}
onClick(event){
// on button click logic here
}
render(){
return (
<button
onClick={this.onClick}>
Click Here
</button>
);
}
}

You write .bind(this) to every method that exists, because most tutorials tell you to do so. If any of your methods use “this”, for example, this.state without using .bind(this), React will throw an error “cannot read the state of undefined”, as these methods do not have access to this. If you have several controlled components, you will end up with a fat stack of .bind(this) codes in your constructor(){}. Do the following:

class LearnReact extends React.Component{onClick = (event) => {
// your on click logic here
}
render(){
return (
<button
onClick={this.onClick}>
Click Here
</button>
);
}
}

This is because ES6’s arrow function uses Lexical Scoping, which lets the method access the this of where it’s triggered.

3. Start reusing event handlers: During my beginner years of using react, I had to write or repeat similar code again and again. If you don’t feel like typing the same thing over and over again, reusing an event handler could be an option:

class ReactApp extends Component {constructor(props) {
super(props);
this.state = {
good: "",
bad: "",
};
}
// Common handler for all inputs
onChange = e => {
const {
target: { value, name },
} = e;

// name will be the state name
this.setState({
[name]: value
});
};

render() {
return (
<div>
<input name="good" onChange={this.onChange} />
<input name="bad" onChange={this.onChange} />
</div>
);
}
}

4. setState() is asynchronous: The innocent me would write code something like this:

Class ReactApp extends React.Component {
constructor(props) {
super(props);
this.state = {
isHappy: false
};
}
toggleHandle= () => {
this.setState({
isHappy: !this.state.isHappy
});
this.toggleMood();
};

toggleMood= () => {
// this.state.isHappy should be true, but it's not
if (this.state.isHappy) {
// Do some Drama
}
};
}

The smarter me would do something like this:

toggleHandle= () => {
this.setState((prevState) => ({
isHappy: !prevState.isHappy
}), () => {
this.toggleMood();
});
};
toggleMood= () => {
if (this.state.isHappy) {
// Do some Drama
}
};

5. Conditional rendering is awesome!

Often we need to add conditional rendering logic in our components. Let’s think of a case of when you want to render a login button if the user hasn’t entered his credentials yet, and log out if the user is already signed in.

Quick and nice way of doing that is using a ternary operator that looks at the evaluated condition isLoggedIn in our case and if it’s true - returns the block after ?, if false - after :.

isLoggedIn = true
isLoggedIn ? <LogoutComponent/> : <LoginComponent>

What if you want to render just one element according to some condition?

Let’s think of a case where we get a response from the server with a list of students and want to display <Table/> component if the list is of at least length 1. If not we don’t want to use it at all.

We can again use ternary operator but provide null as a returned statement if there are no messages. In JSX it will mean that our <Table/> won’t render at all.

studentsList.length ? <Table/> : null

But in this case ternary operator is redundant and we can shorten our conditional rendering with short circuit operator which is a neat javascript hack.

studentsList.length && <Table/>

The above-mentioned code works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false. These are known as short circuit operators.

6. You can destructure states and props:

When you are just starting you will probably usethis.state and this.props too much and I know how tedious it can be to type tens of this.props with different prop names in dozens of components.

However, you can use object destructing to allow a simpler approach to accessing your props and state in render method. In our render method of the class component in React, we can get our props once and use them just with name, ageand date rather than this.props.name etc. with the following code:

const {name, age, date} = this.props

Same goes with the state:

const {name, age, date} = this.state

In our functional components, we can also destructure our props and it looks even cleaner and easier there:

Let’s refactor this code and suddenly we need to write less boilerplate.

const Component = ({coder}) => {
return (
<div>
<ul>
<li>{coder.name}</li>
<li>{coder.age}</li>
</ul>
</div>

You can also do nested destructuring which means you can access name and age from the coderand use them as easy as that.

const Component = ({coder: { name, age }}) => {
return (
<div>
<ul>
<li>{name}</li>
<li>{age}</li>
</ul>
</div>

caution: Make sure you do not have the same names for props and state.

I really hope that I at least tempted you to try out a couple of those things if you haven’t heard of them before. Let us know through comments if you know of other things that can be included in the list :)

Thanks for reading!!!!

--

--

Kunal Mehta

Avid Reader, amateur storyteller, a crazy traveller and by all means a software developer :)