Table of Content
1. Introduction 2. Best React Practices
3. Final Thoughts IntroductionUndoubtedly, the popularity of React.js is continuously increasing in such a short time. Writing clean and brief code is important to improve the code quality and testing becomes much easier. React.js is an open-source JavaScript framework to create interactive user interfaces and UI components making the process of application development successful by following the right approach and top-notch development services. Are you planning to develop an app using the React development services, but find it a challenging task? If so, then follow the best way to examine the power of following the best React.js practices for web development. While I was busy searching regarding why developers should follow React.js practices, I came across an interesting article and couldn’t stop myself from sharing some insights with you all. They mentioned: Best practices for web development are defined as distinct procedures, processes, or techniques in any industrial or corporate setting. If a business follows best practice recommendations, they are likely to have fewer issues or roadblocks in the future. Best practices are widely employed in a variety of industries, including software engineering, project management, and even human resource management. Click here to read more about React.js best practices. Developers can create complex and large web applications that can modify the data without reloading the page again and again which makes the process fast, scalable, and simple. Best React Practices1. Use Dependency InjectionIf you have ever worked with React, you must have come across dependency injection. Using dependency injection is one of the best design practices that every developer should follow. With dependency injection, you can avoid a lot of redundant code in the application while initializing the services and configuration. The example given below shows the use of dependency injection to manage the injection of service layer code into components using Jimple. import Jimple from 'jimple'; import { UsersService } from './services/UsersService'; export let container = new Jimple(); container.set('API_URL', function (c) { return 'http://localhost:8080/api'; }); container.set('API_VERSION', function (c) { return '1.0.0'; }); container.set('USERS_SERVICE', function (c) { return new UsersService(c.get('API_URL'), c.get('API_VERSION')); }); On the Router component, inject the container and define a function called createElement as shown in the code given below: import { Router, IndexRedirect, Route, History } from 'react-router'; import { container } from './container'; class MoneyApp extends React.Component { render() { return <div>{this.props.children}</div> } } // Pass container as prop to children components function createElement(Component, props) { return <Component container={container} {...props}/> } render(( <Router history={history} createElement={createElement}> <Route path="/" component={MyApp}> <Route path="/login" component={Login} /> <Route path="/dashboard" component={Dashboard}> <Route path="/dashboard/overview" component={Overview} /> </Route> <IndexRedirect to="dashboard" /> </Route> </Router>), document.getElementById('app')); Lastly retrieve the dependencies: class Overview extends React.Component { constructor() { super(); this.state = { pending: [], lastMonths: [] } } componentDidMount() { let service = this.props.container.get('SERVICE'); service.yourMethod(); } render() { return <div><span>Some content</span></div> } } Source 2. Use Custom HooksMake sure that a React component is only displayed when a user login into your application and do some sanity checks to discover something. To DRY your code, you have to write custom hooks as shown in the box: import { useEffect } from 'react'; import { useAuth } from './use-auth-from-context-or-state-management.js'; import { useHistory } from 'react-router-dom'; function useRequireAuth(redirectUrl = "/signup") { const auth = useAuth(); const history = useHistory(); // If auth.user is false that means we're not // logged in and should redirect. useEffect(() => { if (auth.user === false) { history.push(redirectUrl); } }, [auth, history]); return auth; } Source Here we are using the useRequireAuth to check whether the user is active and should be redirected to a different page that is provided via state management. 3. Consolidate duplicate code – DRY your codeOne of the most common coding rules is to keep it as simple and concise as possible. And to achieve this, you need to examine and understand the code to identify the structure and similarities. If you find any redundant code in the pattern, there's scope to avoid the unwanted code and make it more concise. const buttons = ['facebook', 'twitter', 'youtube']; return ( <div> { buttons.map( (button) => { return ( <IconButton onClick={doStuff( button )} iconClass={button} /> ); } ) } </div> ); Source 4. Function as childrenIt is a complex task to create a collapsible table row and render the collapse button. But if you're using JSX 2.0, it becomes much easier to return an array instead of one tag. Here is the example that shows the use case for the function as children: export default function Table({ children }) { return ( <table> <thead> <tr> <th>Just a table</th> </tr> </thead> {children} </table> ); } The your collapsible table body will look like: import { useState } from 'react'; export default function CollapsibleTableBody({ children }) { const [collapsed, setCollapsed] = useState(false); const toggleCollapse = () => { setCollapsed(!collapsed); }; return ( <tbody> {children(collapsed, toggleCollapse)} </tbody> ); } Else, you can use this component as shown in the picture: <Table> <CollapsibleTableBody> {(collapsed, toggleCollapse) => { if (collapsed) { return ( <tr> <td> <button onClick={toggleCollapse}>Open</button> </td> </tr> ); } else { return ( <tr> <td> <button onClick={toggleCollapse}>Closed</button> </td> <td>CollapsedContent</td> </tr> ); } }} </CollapsibleTableBody> </Table> Source Now pass the function as children to call the parent component. This method is also called the render callback process or a render prop. 5. Use event handler nameIn a single input field, you have to write in a function called onFirsrInputChange to gather the contents of your Input field. It is not possible to write ten event handlers if you’re already having a form with ten input fields. You can use the name property to access the fields using event handlers. export default class App extends React.Component { constructor(props) { super(props); this.state = { item1: "", item2: "", items: "", errorMsg: "" }; this.onFirstInputChange = this.onFirstInputChange.bind(this); this.onSecondInputChange = this.onSecondInputChange.bind(this); } onFirstInputChange(event) { const value = event.target.value; this.setState({ item1: value }); } onSecondInputChange(event) { const value = event.target.value; this.setState({ item2: value }); } render() { return ( <div> <div className="input-section"> {this.state.errorMsg && ( <p className="error-msg">{this.state.errorMsg}</p> )} <input type="text" name="item1" placeholder="Enter text" value={this.state.item1} onChange={this.onFirstInputChange} /> <input type="text" name="item2" placeholder="Enter more text" value={this.state.item2} onChange={this.onSecondInputChange} /> </div> </div> ); } } The event handler function is used to update the state and deal with various form elements to write a new function for each event. Let us try to untangle this situation using a name field and access the value by event.target.name property that will create a single function to handle both concurrent events. onInputChange = (event) => { const name = event.target.name; const value = event.target.value; this.setState({ [name]: value }); }; Source Final Thought As we all know, React is becoming highly popular because it offers simplicity and flexibility to code as well as provides out-of-the-box benefits while developing an app. Developers highly recommend React.js to create amazing user interfaces and also mentioned that the future of React is bright. More than 90,000 sites are already utilizing React for web development which is expected to grow in the future.
0 Comments
Leave a Reply. |
|