Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force update child component from parent component in reactjs

I need to re-render child component when parent state is changed

In parent Component in setting up the language Once language changes child also to be update with the selected languaue

Parent.js

import React, { Component } from "react";
import Child from "./Child.js";

class Parent extends Component {
  constructor(props) {
    super(props);    
    this.state ={
        lblName: "Name",
        lblGender: "Gender",
        lblDOB: "Date Of Birth",
        lblNatio: "Nationality",
      };
  }
    ChangeLanguage(lang, e){
      if(lang === "en"){
           this.setState(
           {
              lblName: "Name",
              lblGender: "Gender",
              lblDOB: "Date Of Birth",
              lblNatio: "Nationality",
           });
      }
      else if(lang === "sp"){
           this.setState(
           {
              lblName: "Nombre",
              lblGender: "Género",
              lblDOB: "Fecha de nacimiento",
              lblNatio: "Nacionalidad",
           });
      }

    }
    render() {    
    return (
        <Child ChildData={this.state}>
        <button onClick = {this.ChangeLanguage.bind(this, en)}>English</button>
        <button onClick = {this.ChangeLanguage.bind(this, sp)}>Spanish</button>
    )}
}

Parent state passing to child and making as child component

Child.js

import React, { Component } from "react";


class Parent extends Component {
  constructor(props) {
    super(props);    
    this.state = this.props.ChildData;
  }
    componentWillReceiveProps(nextProps){
        this.forceUpdate();
        this.setState(nextProps.ChildData);
    }

    render() {    
    return (
        <div>
             <div>
                  <label>lblName</label>
                  <input type="Text"></input>
             </div>
             <div>
                  <label>lblGender</label>
                  <input type="Text"></input>
             </div>
             <div>
                  <label>lblDOB</label>
                  <input type="Date"></input>
             </div>
             <div>
                  <label>lblNatio</label>
                  <input type="Text"></input>
             </div>
        </div>
    )}
}

Tried with these 2 solutions forceUpdate and set the state ... i failed I want to update the labels from the parent when ever the language c

like image 284
Nowshad Syed Avatar asked Dec 08 '25 06:12

Nowshad Syed


1 Answers

Just add Props with language into the child control and pass them from parent

like image 55
Viktor Shyrokov Avatar answered Dec 09 '25 20:12

Viktor Shyrokov