Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs getting a state value from a child component

Tags:

reactjs

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!

like image 300
Tim Avatar asked Sep 11 '18 16:09

Tim


1 Answers

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.

like image 150
Murli Prajapati Avatar answered Sep 20 '22 05:09

Murli Prajapati