In the following two codes, There is a child and a parent component. The child component has a TextField, and the parent component has Dropdown, is there a way I can set the TextField's value to whatever I change the Parent Dropdown to? For example, if I selected "Medium", I want to change the child component TextField's value to "Medium". Is this possible?
Here is the Child Component
import * as React from "react";
import { TextField } from 'office-ui-fabric-react/lib/';
const ChildComponent = (props) => {
return(
<TextField
label="Description" required
key="descriptionKey"
styles={props.styles}
value={props.value}
multiline={props.multiline}
onChange={props.onChange}
defaultValue={props.defaultValue}
placeholder={props.placeholder}
/>
);
}
export default ChildComponent;
Here is the Parent Component
import * as React from "react";
import ChildComponent from './ListItem';
import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/';
class ParentComponent extends React.Component {
handleChange = (event) => {
this.setState({
operationType: event.target.value,
})
};
render(){
const riskAssess: IDropdownOption[] = [
{ key: 'high', text: 'High' },
{ key: 'medium', text: 'Medium' },
{ key: 'low', text: 'Low' },
]
return(
<div>
<Dropdown
label="Risk Assessment" required
ariaLabel="Risk"
styles={{ dropdown: { width: 125 } }}
options={riskAssess}
onChange={this._onChange}
/>
<ChildComponent value="This is what I want to change to Dropdown value" />
</div>
);
}
private _onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
this.setState({operationType: item.text})
console.log(event);
};
}
export default ParentComponent;
Yep! Replace "This is what I want to change to Dropdown value"
with {this.state.operationType}
. The curly braces tell JSX that you want a variable to populate that value.
With TypeScript, your components need to define their property and state structures, by adding generic arguments to React.Component:
interface ParentProps = {};
interface ParentState = {
operationType: string;
};
class ParentComponent extends React.Component<ParentProps, ParentState> {
For ChildComponent, you'd want to extend React.FC (short for FunctionalComponent) in a similar way. Since it doesn't define any state, it can forego the second generic argument:
interface ChildProps {
styles?: React.CSSProperties;
value?: string;
multiline?: boolean;
onChange?: React.ChangeEventHandler<HTMLInputElement>
defaultValue?: string;
placeholder?: string;
};
const ChildComponent: React.FC<ChildProps> = (props) => {
Now TypeScript knows what to expect.
TypeScript's precise interface definitions ensure that each component gets only what it allows. It replaces React's PropTypes warnings with enforced compilation errors. It's more complex, having to define all this, but it makes for less error-prone development.