Reactjs getting a state value from a child component

pass state from child to parent react
react hooks pass state to child
react passing data between siblings
react get state from child
react call parent function from child
parent and child component in react
react pass state to child
react state

React newbie back here with another question (lol). I have a function that returns a generic component and I was wondering if it's possible to get the state value from that component? Here is what I'm trying to do:

EDIT: I've updated some of my code according to responses

class CreateTable extends Component {
   constructor(props) {
        super(props_;

        this.state = { elements: [] };
    }

    handleCreateTable() {
        var elements = this.state.elements; // []
        elements.push(<TextInput key={"TableName"} label="Table Name" />)'
        elements.push(
                <DataTable
                    tableName = { elements[0].value } // <--- I'd like to do something like this
                />
            );
        this.setState({ elements: elements })
    }
}

TextInput has a child TextField

Thank you for your help!

What I'm trying to do is take some input table name from a user and display it.

The way you could achieve this is by making your TextInput component calling a function passed by the parent with the current value it is having. So your TextInput might look like this:

export default class TextInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };
  }

  handleOnChange = e => {
    const inputText = e.target.value;
    this.setState({
      value: inputText
    });
    this.props.onChange(inputText);
  };

  render() {
    return <input value={this.state.value} onChange={this.handleOnChange} />;
  }
}  

And parent component must pass a function as a prop so that it can know of the changes happening in the child.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tableName: ""
    };
  }
  onInputChage = value => {
    this.setState({
      tableName: value
    });
    console.log("I am Parent component. I got", value, "from my child.");
  };
  render() {
    return (
      <div className="App">
        <TextInput onChange={this.onInputChage} />
        <span>Table:{this.state.tableName}</span>
      </div>
    );
  }
}   

App component is passing onInputChage function to TextInput through onChange prop. Prop name onChange can be anything.

Here is working code sandbox link to test this code.

Passing Data Between React Components - Ruth M. Pardee, How do you pass state value to another component react? Then the parent passes values from its state as props to its child components. If a parent component needs to know about events that happen in its children, then you should pass a callback from the parent to the child. Then the child calls this function when an event occurs to notify the parent which can then update its state.

I have a function that returns a generic component and I was wondering if it's possible to get the state value from that component?

This is not the React way. Instead you should design your components so that the parent keeps all state that it needs. Then the parent passes values from its state as props to its child components.

If a parent component needs to know about events that happen in its children, then you should pass a callback from the parent to the child. Then the child calls this function when an event occurs to notify the parent which can then update its state.

In addition, state should only contain data, not JSX components. You can store a list of data in state and iterate over it in render() to create the necessary components. So for example, if you have a method that calls

this.setState({items: ['foo', 'bar']});

Then in render, you can do something like

return <div>
    {this.state.map(item => <DataTable name={item}/>}
    </div>

How to access child's state in React?, it as a prop to the other child (see above example). The sibling can then use the data as a prop. You can use a callback, passed in via props to your child component to pass state to the parent component – Dacre Denny Jul 26 '18 at 22:31 The user enters a number into input, and when they click the button i need the value of the input passed to the state in the top-level component – HJW Jul 26 '18 at 22:34

It's actually possible, by passing object and setting object attribute in child component

const TextInput = props => {
    let holder = {
        getChildState: null
    };

    return (
        <div>
            <TextBox {...props} type="text" multiline={false} id={generateId()} holder={ holder }/>
        </div>
    );
}

class TextBox extends Component {
  constructor(props) {
    super(props);

    this.state = {
        value: null,
        error: false,
        errorMsg: null,
    };

    this.props.holder.getChildState = () => this.state;
  }

  ....
}

So if your TextInput would be more complex, than you would use holder.getChildState(), but it would be available only after TextBox constructed.

There is also other possibility to use emitter.

But you definitely should be sure what you are doing, because it is more simple and convenient to use only down direction props sharing especially considering that this is react philosophy. If you feel that some component should report its state to few other you may try redux

How to access childs state from parent component in React, If you do indeed wish to access the state of a component's children, you can is a change in the state of the input field(child) we are getting the value from the  ReactJs is a powerful library allows to use component inside another component, sometime you may need to change state of the parent component from a child component. to do this communication between the child and parent, you can use a function on child component as a Prop, when this function is called will be detected on parent component that allows

Passing Data Between React Components, Get state value onClick event. One method is to update state, and when a click happens, use a callback function that gives the parent component the values. setState () schedules an update to a component’s state object. When state changes, the component responds by re-rendering. props (short for “properties”) and state are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way: props get passed to the component

Component State – React, Data handling in React could be a bit tricky, but not as complicated as it might seem. Method 2: Use a global store maintaining the states of all child components setState({ message: value })}}> {this.props.children} //this indicates that the (b) To view/access the data by Child2, it has to access Provider to get the states. The state of this parent component has the messageShown property that we want to change for some reason from the Child component. In the parent we'll render the Child component and we'll send as a property (in this case action) the handler function declared in the parent.

React.js updating parent's state from child component, setState() schedules an update to a component's state object. way: props get passed to the component (similar to function parameters) whereas state is In React, both this.props and this.state represent the rendered values, i.e. what's This ensures, for example, that if both Parent and Child call setState during a click  Step1: Create a Provider Component for the two children. This Provider mantains the state (data to be used by both components and some callback used to manipulate the states) and returns a contextObject.Provider JSX component ) Step 2: Pass the state and the callback function as props to all children inside the Provider Component.

Comments
  • Be careful about editing your code once there are answers because the answers might no longer make sense. Instead you should strongly consider posting a new question, possibly with a link to your old, related question.
  • @Tim you must not put jsx/components in state.
  • @MurliPrajapati thanks for the advice. Is there another way I can "insert" a component?
  • @Code-Apprentice thanks- I'll do that
  • I will vote up, now it is good one. But i think it should be another question. because now my answer looks like not from here
  • Thanks a ton Murli! This helped solve my problem :-) Thanks for the quick responses as well
  • Thank you for keeping me from going down the wrong path. So what you're suggesting is that for every input component that uses the generic <Input/> component, e.g.<TextInput/>, <NumberInput/>, <TextField/> , I should have them maintain their own state?
  • I totally agree. This example is not reallife code example, just a demonstration of javascript possibility