I have three components, App, TextBox and Keyboard.
What I am trying to do is:
- User clicks on one of the buttons on keyboard.jsx, a child component
- Pass the associated character to App.js (this works, via callback functions)
- Once a new character has been passed to App.js, update the other child component, TextBox.jsx, by passing it the new value.
However, I am stuck at step 3. I have the value passed to App.js, but I don't know how to pass it to the child component, Keyboard.jsx, so i can update the input form.
Here is my code:
keyboard.jsx
import React, { Component } from "react";
class Keyboard extends Component {
state = {
current: null,
keys: ["á", "é", "í", "ñ", "ó", "ú", "ü"]
};
render() {
return (
<div>
<table>
<tbody>
{Object(
this.state.keys.map(key => {
return (
<td>
<button
onClick={() => {
this.solve(key, this.props.handler);
}}
>
{key}
</button>
</td>
);
})
)}
</tbody>
</table>
</div>
);
}
solve = (char, callback) => {
this.setState({ current: char });
callback(char);
return;
};
}
export default Keyboard;
textbox.jsx
import React, { Component } from "react";
class TextBox extends Component {
state = { equation: null };
render() {
return (
<div>
<form onSubmit={this.mySubmitHandler}>
<input
size="35"
type="text"
name="equation"
onChange={this.handleInputChange}
/>
</form>
</div>
);
}
handleInputChange = event => {
event.preventDefault();
this.setState({
[event.target.name]: event.target.value
});
};
mySubmitHandler = event => {
event.preventDefault();
this.setState({ equation: event.target.value });
alert("You are submitting " + this.state.equation);
console.log(this.state.equation);
};
}
export default TextBox;
App.js
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import Keyboard from "./components/keyboard";
import TextBox from "./components/textbox";
class App extends Component {
state = { character: null };
render() {
return (
<div>
<TextBox />
<Keyboard handler={this.handler} />
</div>
);
}
handler = arg => {
console.log(arg);
};
}
export default App;