logo
down
shadow

Child component does not set the initial value passed from the parent: ReactJS


Child component does not set the initial value passed from the parent: ReactJS

Content Index :

Child component does not set the initial value passed from the parent: ReactJS
Tag : javascript , By : Genipro
Date : January 12 2021, 01:40 AM

it should still fix some issue A way to solve this is to control parent and child switches from master component. Checkout the working forked codesandbox
APP
import React from "react";
import ReactDOM from "react-dom";
import ChildSwitch from "./ChildSwitch";
import ParentSwitch from "./ParentSwitch";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      parentVal: "disabled",
      switch1Val: "enabled",
      switch2Val: "disabled",
      switch3Val: "enabled"
    };
  }

  componentDidMount() {
    this.setParentSwitchValue();
  }

  onGetChildSwitchValues = () => {
    console.log(this.state);
  };

  setChildSwitchValue = (whichSwitch, selected) => {
    this.setState(
      prevState => ({ ...prevState, [whichSwitch]: selected }),
      this.setParentSwitchValue
    );
  };

  setParentSwitchValue = () => {
    const { switch1Val, switch2Val, switch3Val } = this.state;
    const switchStates = [switch1Val, switch2Val, switch3Val];
    let parent = "pending";

    if (switchStates.every(val => val === "enabled")) {
      parent = "enabled";
    }

    if (switchStates.every(val => val === "disabled")) {
      parent = "disabled";
    }

    this.setState(prevState => ({ ...prevState, parentVal: parent }));
  };

  render() {
    const { parentVal, switch1Val, switch2Val, switch3Val } = this.state;
    return (
      <>
        Parent Switch :{" "}
        <ParentSwitch
          parentSwitch={parentVal}
          onSelect={this.setParentSwitchValue}
        />
        Child Switches :
        <ChildSwitch
          switchName={"switch1Val"}
          selected={switch1Val}
          onSelect={this.setChildSwitchValue}
        />
        <ChildSwitch
          switchName={"switch2Val"}
          selected={switch2Val}
          onSelect={this.setChildSwitchValue}
        />
        <ChildSwitch
          switchName={"switch3Val"}
          selected={switch3Val}
          onSelect={this.setChildSwitchValue}
        />
        <button onClick={this.onGetChildSwitchValues}>Get Child Values</button>
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import MultiToggle from "react-multi-toggle";
import React from "react";
import "react-multi-toggle/style.css";

class ParentSwitch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: [
        {
          displayName: "Disabled",
          value: "disabled",
          optionClass: "red"
        },
        {
          displayName: "Pending",
          value: "pending",
          optionClass: "grey"
        },
        {
          displayName: "Enabled",
          value: "enabled",
          optionClass: "green"
        }
      ]
    };
  }

  render() {
    const { options } = this.state;
    return (
      <MultiToggle
        options={options}
        selectedOption={this.props.parentSwitch}
        onSelectOption={() => {}}
      />
    );
  }
}

export default ParentSwitch;
import MultiToggle from "react-multi-toggle";
import React from "react";
import "react-multi-toggle/style.css";

class ParentSwitch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: [
        {
          displayName: "Disabled",
          value: "disabled",
          optionClass: "red"
        },
        {
          displayName: "Pending",
          value: "pending",
          optionClass: "grey"
        },
        {
          displayName: "Enabled",
          value: "enabled",
          optionClass: "green"
        }
      ]
    };
  }

  render() {
    const { options } = this.state;
    return (
      <MultiToggle
        options={options}
        selectedOption={this.props.parentSwitch}
        onSelectOption={() => {}}
      />
    );
  }
}

export default ParentSwitch;

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

ReactJS onClick arguments not getting passed to parent component


Tag : javascript , By : user186876
Date : March 29 2020, 07:55 AM
I wish this help you I think you should pass the function itself, not "invoke the function". Delete () here.
<ProfileDetails
    {...this.props.uiStore.profile}
    updateNotifications={this.updateNotifications}
/>

How to setState in child component when child function called from parent component in ReactJS


Tag : reactjs , By : Aires
Date : March 29 2020, 07:55 AM
will be helpful for those in need The problem seems to be that when calling setState inside the getAlert function of child, this.setState will come undefined. This happens because this inside your getAlert function doesn't refer to the context of the React Component and setState is defined for the Component. You can solve this by binding the getAlert function.
You can do it in two ways.
class Child extends Component {

  constructor() {
     super();
     this.getAlert = this.getAlert.bind(this);
  }
  getAlert() {
    alert('clicked');
    //HERE I NEED TO SETSTATE 
  }

  render() {
    return (
      <h1>Hello</h1>
    );
  }
}
getAlert = ()  => {
    alert('clicked');
    //HERE I NEED TO SETSTATE 
  }
class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>
      </div>
    );
  }
}

class Child extends React.Component {
  constructor(){
     super();
     this.state = {message:""};
  }

  getAlert = () => {
    alert('clicked');
    this.setState({message: "somemessage"});
  }

  render() {
    return (
      <div>{this.state.message!=""?(
         <h1>{this.state.message}</h1>

      ):(

      <h1>Hello</h1>

      )}</div>
    );
  }
}

ReactDOM.render(<Parent/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>

Get current state of child component through prop passed by Parent - Reactjs


Tag : reactjs , By : Mahesh
Date : March 29 2020, 07:55 AM
hope this fix your issue Parent component cannot query the state of the child component. At least, that's not the intended design of React.
What I think you're asking is how to coordinate the state of child with parent, and you're on the right track to use a prop to pass the state from child to parent.
class Parent extends React.Component {
  state = { name: "John" }
  handleChildAnimal = animal => 
    this.setState({ animal });
  handleClick = e => 
    console.log(`Child animal: ${this.state.animal}`);
  render() {
    return (
      <div>
        <Child onAnimal={this.handleChildAnimal} />
        <button onClick={this.handleClick}>Tell me Animal state</button>
      </div>
    );
  }
}

class Child extends React.Component {
  state = { animal: "Lion" }
  handleClick = e => {
    console.log(`Animal: ${this.state.animal}`);
    this.props.onAnimal(this.state.animal);
  }
  render() {
    return (
      <button onClick={this.handleClick}>{this.state.animal}</button>
    );
  }
}

ReactJS - How can I properly render content that originates in a parent component and is passed down to a child componen


Tag : javascript , By : Matt
Date : March 29 2020, 07:55 AM
around this issue I can't seem to render my column names in the CarTable.tsx when the order array of strings is passed down as prop to this component. I know it's some quirky asynchronous programming. Also when I click the button, the order of column names should change and this change should be reflected in a re-render. , In CarTable constructor, remove
this.setState({
    cars: this.props.cars,
    columnOrder: this.props.order
});

Child component's local state changes when change happens inside parent component : ReactJS


Tag : javascript , By : Nick Coats
Date : March 29 2020, 07:55 AM
may help you . Sorry, my here below answer was wrong.
In your main component, you set your state.columns just once, when the component did mount. It will never be changed after.
...
constructor(props) {
    super(props);
    this.state = {
      data: [
        { firstName: "Jack", status: "Submitted", age: "14" },
        { firstName: "Simon", status: "Pending", age: "15" },
        { firstName: "Pete", status: "Approved", age: "16" },
        { firstName: "Lucas", status: "Rejected", age: "19" }
      ],
      selectedValues: {},
    };
  }
...
buildColumns = ({ data, selectedValues = {} }) => {
    const { firstName, status } = selectedValues
    return [
      {
        Header: () => (
          <div>
            <div style={{ position: "absolute", marginLeft: "10px" }}>
              <Child
                key="firstName"
                name="firstName"
                options={this.getValuesFromKey(data, "firstName")}
                selectedOption={firstName}
                handleFilter={this.handleFilter}
              />
            </div>
            <span>First Name</span>
          </div>
        ),
        accessor: "firstName",
        sortable: false,
        show: true,
        displayValue: " First Name"
      },
      {
        Header: () => (
          <div>
            <div style={{ position: "absolute", marginLeft: "10px" }}>
              <Child
                key="status"
                name="status"
                options={this.getValuesFromKey(data, "status")}
                selectedOption={status}
                handleFilter={this.handleFilter}
              />
            </div>
            <span>Status</span>
          </div>
        ),
        accessor: "status",
        sortable: false
      },
      {
        Header: "Age",
        accessor: "age"
      }
    ];
  }

  render() {
    const { data, selectedValues } = this.state;
    const columns = this.buildColumns({ data, selectedValues })
    return (
      <div>
        <ReactTable
          data={data}
          columns={columns}
          defaultPageSize={10}
          className="-striped -highlight"
        />
      </div>
    );
  }
Related Posts Related QUESTIONS :
  • TypeScript interface signature "(): string"
  • Is synchronous XMLHttpRequest supported in Internet Explorer 10 and 11?
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • React not updating state with setState correctly inside promises
  • Direct native JavaScript or jQuery method to get containing block of an element
  • Dynamic JSON object to Html Table
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • How to block scroll event passing through to iframe until iframe is active?
  • What is the purpose of "constructor" method in javascript?
  • Stencil JS not working with non-default imports
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com