Tips for updating a functional component when the parent state changes

Is there a way to trigger a re-render of a functional child component when the parent state changes? When dealing with a class component as a child, I can use componentWillReceiveProps to solve this issue. However, my child component is a functional one.

Here's the scenario: I have a table component with radio buttons on the page. Selecting a specific radio button successfully changes the table content. But if I'm on the 4th page of the table and switch to another radio button, causing a change in the table length, I want to be taken back to the first page automatically. Unfortunately, the child component does not re-render in this situation. How can I achieve this?

This code snippet demonstrates the setup:

Parent Component:

export default class Report extends Component {
  constructor() {
    super();
    this.state = {
        table_data:[],
        page: 0,
        analys_type: "1"
    }
  }
  setData = () => {
    ......
    ......
  }

  handleChangeAnalysType = (event) => {
      this.setState({
          analys_type: event.target.value,
          page: 0
      }, () => {
          this.setData();
      });
  }
  render() {
       <div>
           <Paper className="input-box">
                <div>
                     <FormControl component="fieldset">
                          <RadioGroup name="analys_type" value={this.state.analys_type} onChange={this.handleChangeAnalysType}>
                               <FormControlLabel value="1" control={<Radio />} label="Day" />
                               <FormControlLabel value="2" control={<Radio />} label="Week" />
                               <FormControlLabel value="3" control={<Radio />} label="Month" />
                          </RadioGroup>
                      </FormControl>
                  </div>
             </Paper>
             <Paper className="table-box">
                  <AnalysTable table_data={this.state.table_data} analys_type={this.state.analys_type} current_page={this.state.page} />
             </Paper>
       </div>
  }
}

Child Component:

export default function AnalysTable(props) { 
     const [page, setPage] = React.useState(props.current_page);
     const [rowsPerPage, setRowsPerPage] = React.useState(10);
     const handleChangePage = (event, newPage) => {
         setPage(newPage);
     };

     const handleChangeRowsPerPage = (event) => {
           setRowsPerPage(parseInt(event.target.value, 10));
          setPage(0);
     };

     render (
         <div>
              <TableContainer>
               ......
              </TableContainer>
              <TablePagination
                    rowsPerPageOptions={[10, 25, 100]}
                    component="div"
                    count={props.table_data.length}
                    page={page}
                    onChangePage={handleChangePage}
                    rowsPerPage={rowsPerPage}
                    onChangeRowsPerPage={handleChangeRowsPerPage}
                    labelRowsPerPage="rows"
               />
         </div>
     )
}

Answer №1

If you want to update the component state when the parent changes, you can follow this approach:

// Initialize the page state with props.current_page
const [page, setPage] = React.useState(props.current_page);

// Add an effect that updates the page state when props.current_page changes
useEffect(()=>setPage(props.current_page), [props.current_page])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Why isn't the image utilizing all the available space?

I'm working on creating a simple card to display services, with just an image and some text. However, I'm facing an issue where the image is not taking up the full width and height of the container as expected. Could someone help me figure out w ...

Adjusting the width of MuiInputBase-root: a step-by-step guide

I'm currently working on customizing a text input field, but I'm facing an issue with adjusting its width. Specifically, I need to modify the width of the class "MuiInputBase-root MuiInput-root MuiInputBase formControl MuiInput-formControl" as it ...

NextJS: encountered an error with fallback enabled

I have my NextJS setup on Vercel and here is how I configured getStaticPaths: const paths = posts.map((post) => ({ params: { player: post.player, id: post.id }, })) return { paths, fallback: true } However, when I set the fallback to true, I ...

Instructions on how to eliminate the minutes button from Material UI datetime picker

I'm currently working on customizing a datetimepicker from materialUI in ReactJS. My goal is to prevent the user from seeing or selecting minutes in the picker interface. Despite setting the views prop to include only year, month, date, and hours, use ...

The styles order definition in the Material-UI production build may vary from that in development

When using material-ui, an issue arises in the production build where the generated styles differ from those in development. The order of the material-ui styles in production does not match the order in development. In DEV, the material-ui styles are defi ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...

The CORS problem arises only in production when using NextJS/ReactJS with Vercel, where the request is being blocked due to the absence of the 'Access-Control-Allow-Origin' header

I've encountered a CORS error while trying to call an API endpoint from a function. Strangely, the error only occurs in production on Vercel; everything works fine on localhost. The CORS error message: Access to fetch at 'https://myurl.com/api/p ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

How can we determine which MenuItems to open onClick in a material-ui Appbar with multiple Menus in a React application?

While following the examples provided on the material UI site, I successfully created an AppBar with a menu that works well with one dropdown. However, upon attempting to add a second dropdown menu, I encountered an issue where clicking either icon resulte ...

The issue of React Js's inline style malfunctioning when using a loop condition

Having some trouble with setting different backgrounds for items in a loop in React JS. I attempted to use inline styles to make it dynamic, but no luck so far. Any tips or solutions? { main.map((item, index) => ( <a key={index} href=&apo ...

React - Display a menu when a single item from a list of items is clicked

I am experiencing an issue with the sliding menu appearing in every item instead of just one. Whenever I click on the config button, the menu displays for each item. I tried passing props {mail.id} to resolve this, but I seem to be missing something impor ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

What is the process for deploying a React project located in a subdirectory of the main branch to Github Pages?

Currently, the project repository is structured like this: main: app/ README.md preview.jpg The app directory contains all the necessary files and folders for my react project. I am facing an issue with getting Github Pages to work properly with the sub- ...

Unable to include query parameters in the nextjs dynamic route

I have a file called [slug].js. What I am attempting to do is add a query parameter to this dynamic route. Here's the code: await router.replace({ pathname: `${router.pathname}`, query: { coupon }, }, undefined, ...

in javascript, how can you access the value of a parent object within a nested object?

Within the material ui framework, I am utilizing the createMuiTheme function to create a theme. How can I access the values of the parent object within a nested object? (I am aware that I can declare global variables above the function); To better unders ...

During my attempt to incorporate Tailwind CSS into my React Js project, I encountered a pesky error

While attempting to integrate Tailwind into my React Js project using Postcss and autoprefixer, I encountered an issue. Immediately after running npm start or npm run start, the following error occurred: npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! ...

Tips for customizing an Alert component in a React Native application

I've been working on developing an Alert element using react-native. I have successfully created it with the following code: Alert.alert( 'Warning', 'bla bla bla', [ {text: 'OK', onPress: () => ...

Error when testing React Material UI: TypeError - Attempting to read property 'get' of undefined

I encountered an issue with the following code snippet: /* eslint-disable react/display-name */ import { Box, Button, LinearProgress, makeStyles } from '@material-ui/core'; import { Refresh } from '@material-ui/icons'; import { SearchHi ...

In order to access the latest version on Google Cloud (App Engine), I must first clear my cookies

Recently, I started using Google Cloud to host my React application. The version of React that I am using is "16.8.3" (although I don't think it's relevant to my issue). The problem arises when I make some updates to the application by running & ...