Search code examples
reactjscomponentsreact-class-based-component

How to update render() of a class-base component using onChange method of an input


I have written these to components that are going to search through a JSON file. The first component consists of two parts 1-it returns elements of JSX representing and 2-it finds matches through the JSON file and fills the data in a Const and passes that to props of the other component which is created to show the results. The problem is that the render() method of the component does not reload the newly entered data whereas variables work properly and data is passed from the first component to the second one without any problem.

import react from 'react';
import React, { Component } from 'react';
import './index.css';
import ResultP from './ResultP';
import userData from './userData';

class SearchP extends Component {
    constructor(props){   
        super(props); 
        this.state = {
        SearchValue : "",
        MatchingItems : []
    }
}

    handleChange = (word)=> {
        const match = word.target.value;
        const Matches =  userData.filter((users) => {return users.name.includes(match);});
        this.setState({MatchingItems : Matches})
        console.log(this.state.MatchingItems);
    };

    render() {
        return (
            <div>
            <form className="my-form" >
            <input type="search" onChange={this.handleChange} 
            placeholder="Write your keyword here" />
            </form>
            <ResultP SearchString = {this.state.MatchingItems} /> 
            </div>
        )
    }
}
export default SearchP;

this one was the first component. Below is the second one

import React, { Component } from 'react';

 class ResultP extends Component {
     constructor(props){
         super (props);
         this.state = {
         SearchString : this.props.SearchString,   
         }
     }
     
    render() {
        return (
             
           <section className="main-section">
             {this.state.SearchString}
            </section>
        
        )
    }
}
export default ResultP;

Solution

  • The constructor logic only executes once when the component is initially rendered, so when you initialize a state variable in the constructor with a prop value, that state variable won't update if the prop value changes. You'll need to add the getDerivedStateFromProps function in your child component: https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops. Here's an example: https://www.tutorialspoint.com/reactjs-getderivedstatefromprops-method