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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With