React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
We can wait for setState
to finish before triggering a function by passing in a function as a 2nd argument of setState
.
For instance, we can write:
this.setState({
firstName,
lastName,
age
}, () => {
console.log(this.state) ;
})
We called setState
with the object with the states first.
Then we run our callback to get the latest value of this.state
.
We can add an external link by passing in a component to redirect to an external link.
For instance, we can write:
<Route path='/external-site' >
{() => {
useEffect(() => {
window.location.href = 'https://example.com';
}, [])
return null;
}}
</Route>
We used the Router
component with the path
prop to set the path.
Then in our component, we redirect to an external URL by setting the URL as the value of window.location.href
.
And we return null
to render nothing.
We can also redirect directly in componentDidMount
:
class RedirectPage extends React.Component {
componentDidMount(){
window.location.replace('http://www.example.com')
}
render(){
return null;
}
}
We can set the hove state by listening to the mouseenter
and mouseleave
events.
For instance, we can write:
<div
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
>
foo
</div>
We can pass in event handlers to the onMouseEnter
and onMouseLeave
props.
Then we can run code within those methods to set the hover state.
We can set the prop types in the functional stateless component.
For instance, we can write:
import React from "react";
import PropTypes from "prop-types";
const Name = ({ name }) => <div>hi {name}</div>;
Name.propTypes = {
name: PropTypes.string
};
Name.defaultProps = {
name: "james"
};
We created the Name
component with the propTypes
property.
Then we set the data type of the name
prop with it.
We can also set the default value for the name
prop.
We’ve to install the propt-types
package to set types for the props.
We can use setTimeout
in React components by calling setTimeout
in componentDidMount
and then clearing the timer within the componentWillMount
method.
#technology #javascript #web-development #software-development #programming #react