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.
How to get Current Route with React Router
We can use the useLocation
hook to get the current route with React Router.
For instance, we can write:
import { useLocation } from 'react-router-dom'
function App() {
const location = useLocation();
return <span>{location.pathname}</span>
}
useLocation
returns the nativelocation
object.
So we can use location.pathname
to get the current route.
With class components, we can use the withRouter
higher-order component to set the location
prop to do the same thing.
For instance, we can write:
import {withRouter} from 'react-router-dom';
const App = withRouter(props => <Foo {...props}/>);
class Foo extends React.Component {
bar() {
const {pathname} = this.props.location;
}
}
We called the withRouter
higher-order component and pass in the props
from there into our Foo
component.
This sets the locations
prop of Foo
to the native location
object.
Then we can get the pathname
for the path.
Services in React Application
A service is just a context-independent piece of code which we can reuse anywhere.
So to make a service in a React app, we can just make a module that exports an object with the shared methods that we want to call.
For instance, we can write:
const HttpService = {
getTodos(value) {
// code to get todos
},
setTodos(value) {
// code to save todos
}
};
export default HttpService;
Then in our component, we can write:
import HttpService from "./services/HttpService.js";
function TodosPage() {
const [todos, setTodos] = useState([]);
const getTodos = async () => {
const todos = await HttpService.getTodos();
setTodos(todos);
}
useEffect(() => {
getTodos()
}, [])
return <Todos todos={todos} />
}
We just import the module and then use the getTodos
method within the export object to get the data we want.
We can do the same thing for any other piece of context-independent shared code.
Disable a Button When an Input is Empty
We can disable a button when an input field is empty by checking the input’s value and determine if we need to disable button.
For instance, we can write:
class EmailForm extends React.Component {
constructor() {
super();
this.state = {
email: '',
};
}
handleEmailChange = (evt) => {
this.setState({ email: evt.target.value });
}
handleSubmit = () => {
const { email } = this.state;
alert(`${email} subscribed`);
}
render() {
const { email} = this.state;
const enabled = email.length > 0;
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Email"
value={this.state.email}
onChange={this.handleEmailChange}
/>
<button disabled={!enabled}>Subscribe</button>
</form>
)
}
}
We created an input for entering an email address.
When we enter something into the input, then the handleEmailChange
method runs.
It sets the email
state which we use in the value
prop of the input and in the render
method for the button enabled check.
We set the enabled
flag by checking if the email’s length is bigger than 0.
This means that something is filled into the box.
Then we set the disabled
prop of the button to be !enabled
to disable it when it’s empty.
The Use of the ‘react-scripts start’ Command
react-scripts
is a set of scripts that’s provided by create-react-app
.
It kicks off our project without configuration, so we don’t have to set up a React project from scratch ourselves.
react-scripts start
sets up the dev environment and runs the dev server and enables hot reloading.
It has React, JSX, ES6, and Flow syntax support.
ES features beyond ES6 like the object spread operator can also be used.
CSS is autoprefixed so that we don’t have to add the prefixes ourselves.
A create-react-app project also comes with a unit test runner.
It’ll also warn us about common developer mistakes.
And it’ll compile the app for us into a production-ready bundle.
It also supports the development of progressive web apps.
All the tolls will be updated when we update create-react-app.
Conclusion
We can create a shared module to reuse context independent code.
create-react-app does a lot for us, so we should use it to create React apps.
There are a few ways to get the current route with React Router.
We can disable a button by setting a boolean expression as the value of the disabled
prop.