score:2
you are causing continuous renders by modifying the state in the render()
function.
instead i would do the following - not using for ismain
state variable:
render() {
let ismain = false;
if (window.location.pathname === '/') {
ismain = true;
} else if (window.location.pathname === '/ourworks') {
ismain = false;
}
return (
<div>
<headercommon ismain={ismain} />
<route path='/' exact component={index} />
<route path='/ourworks' exact component={gallery} />
<footercommon />
</div>
);
}
or even shorter:
render() {
const ismain = window.location.pathname === '/';
return <div>
<headercommon ismain={ismain} />
<route path='/' exact component={index} />
<route path='/ourworks' exact component={gallery} />
<footercommon />
</div>
}
i hope this helps!
score:3
a react hookful solution
an alternative to the class-based solution is involving react's new addition of hooks.
react hooks were introduced in react v16.8 and highly reduce the boilerplate your code requires to initialize and render components.
if you're interested i highly recommend exploring the react hook documentation here.
code
import react, { component, usestate, useeffect } from "react";
import index from './index/layout/layout';
import gallery from './gallery/layout/layout';
import headercommon from './common/header/header';
import footercommon from './common/footer/footer';
import { route } from 'react-router-dom';
export const path = (props) => {
const [ismain, setismain] = usestate(null);
useeffect(() => {
setismain(window.location.pathname === '/')
}, []);
return (
<div>
<headercommon ismain={ismain} />
<route path='/' exact component={index} />
<route path='/ourworks' exact component={gallery} />
<footercommon />
</div>
);
};
the usestate hook
the usestate hook is common-place in react functional components and is imported directly from react with import {usestate} from "react
.
we simply provide a default value in the function expression, e.g. usestate(null)
which will set out initial state to a value of null. we can set this value to be any value, a data structure or an object.
we assign a way to access and set the state with array destructuring:
const [ismain, setismain] = usestate(null);
we can now access our state with calls to ismain or set the state with setismain.
the useeffect hook
the useeffect hook is similar to componentdidmount
and componentdidupdate
lifecycle methods in class-based react. this hook will automatically call depending on the second argument you pass to this hook. if no second argument is supplied, the hook will automatically act as componentdidupdate
.
in the solution above, i pass an empty array ([]) as a second parameter to the useeffect hook callback. this means that the state value only updates on the components initial render and is effectively equivalent to componentdidmount
.
useeffect(() => {
setismain(window.location.pathname === '/')
}, []);
additonally, we can pass values into this array to tell react when the component should re-render, but that's outside the scope of this answer.
again, much more details about the usestate hook, useeffect hook, and react hooks in general can be found in the docs.
Source: stackoverflow.com
Related Query
- What is the best way to write this React code?
- What would be the best way to refactor this React component and keep it DRY?
- What is the best way to optimize this React component to make it reusable?
- What is the best way to access redux store outside a react component?
- What is the best way to redirect a page using React Router?
- What is the best way to trigger onchange event in react js
- What is the best way to deal with a fetch error in react redux?
- React - What is the best way to handle login and authentication?
- What is the best way to secure Firebase API keys in a react app so it is not accessible publicly?
- What is the best way to implement undo state change (undo store/history implementation) in React Redux
- What is the best way to do Error Handling in React Native App.
- What is the best way to update my react state when data in database changes?
- React styled-component / e2e testing: What is the best way to use css selector?
- React - What is the Best Way to use Multiple createContexts?
- What is the best way to save my dynamicly created data using React and Javascript?
- what is the best way to use react router V6 navigation with redux and redux thunk actions?
- What is the best way for connecting Django models choice fields with React js select options
- What is the best way to apply layout styling to styled-components and React components used in different places on a site?
- what is the best way to deploy react app in lan only
- What the best way to loading data to a cart react js with context api
- What is the best way to include css files for Prime React components when using Parceljs?
- What is the best way to create component library for both React and Preact?
- What are the best react hooks, frequency code or performance
- What is the best way to trigger an redux action if the props changed after the react 16.3?
- React - What is the best way to change an elements text each time the user clicks anywhere on screen?
- Is there a simpler way to write this React code
- What is the equivalent of this way of looping over an object in React
- What is the best way to structure api config file in react project?
- What is the best way to test methods that traverse the react components
- what is the best way to show some piece of code or snippet in component template using ReactJS App?
More Query from same tag
- Populating data on a table in React
- How to implement vertical scrolling of a grid items within a grid in material ui?
- Syncfusion tab control's value doesn't refresh when value of elements changes
- ChunkLoadError: Loading chunk XY failed. - Randomly getting fatal on PRODUCTION
- failed to map state to props in reactjs
- React & Typescript component props type for `Component`
- How can I get the correct ID assigned to the delete function
- React JS: onWheel bubbling stopPropagation not working
- How to retain props.location.state value if I refreshed
- React.Component vs React.createClass
- react - add icons to header inside component
- Change text color in Semantic UI button Component
- Convert object to array in Javascript / React
- Writing "getInitialState" using ES6 standards
- React bootstrap CSS Unexpected Token
- How to generate sitemap with react router
- Best approach to display updated list in React via fetch again or through some other way
- SetState not forcing a rerender on a functional component?
- Unable to call useContext within a functional component
- Default function value in React component using Typescript
- nodejs reactjs and webpack, config is wrong but what?
- Is there a better way to get different data from an API in the same component based on data type?
- axios post request error with 422 (Unprocessable Entity) from react
- issues with array of objects from variable in React render methodq
- How do I access React component's local state using Cypress?
- Render Props - React Route
- How to setState in React only after multiple fetches inside a loop are resolved
- loading gltf file in nextjs using 'react-3d-viewer'
- How to call updateProfile() after creating User
- How would you implement useCallback using useState from scratch?