forked from M-Labs/web2019
69 lines
2.6 KiB
JavaScript
69 lines
2.6 KiB
JavaScript
import React, {Component} from "react";
|
|
import {Tip} from "./Tip";
|
|
|
|
class Radio extends Component {
|
|
constructor(props) {
|
|
super(props);
|
|
// Initialize the state object with the initial values from the props
|
|
this.state = {
|
|
variant: props.outvar in props.data ? props.data[props.outvar] : props.variants[props.fallback ? props.fallback : 0],
|
|
};
|
|
|
|
// Bind the event handler to this
|
|
this.handleClick = this.handleClick.bind(this);
|
|
this.props.target.construct(this.props.outvar, this.state.variant);
|
|
}
|
|
|
|
handleClick(variant) {
|
|
// Update the state object with the new value for outvar
|
|
this.setState({
|
|
...this.state,
|
|
variant: variant
|
|
});
|
|
this.props.target.update(this.props.outvar, variant);
|
|
}
|
|
|
|
static getDerivedStateFromProps(props, current_state) {
|
|
if (current_state.variant !== props.data[props.outvar]) {
|
|
return {
|
|
variant: props.data[props.outvar]
|
|
}
|
|
}
|
|
return null
|
|
}
|
|
|
|
render() {
|
|
let key = this.props.id + this.props.outvar;
|
|
return (
|
|
<div className="shop-radio" key={this.props.id}>
|
|
<div style={{"display": "inline"}}>
|
|
{this.props.icon && <img src={`/images${this.props.icon}`} className="options-icon"/>}
|
|
{this.props.title}
|
|
</div>
|
|
{this.props.tip && <Tip id={this.props.id + "tooltip"} tip={this.props.tip}/>}
|
|
{this.props.variants.map((variant, _) => (
|
|
<div className="form-check" key={key + variant}>
|
|
<input
|
|
className="form-check-input"
|
|
type="radio"
|
|
name={key}
|
|
id={key + variant}
|
|
checked={this.state.variant === variant}
|
|
onClick={() => this.handleClick(variant)}
|
|
onChange={() => this.handleClick(variant)}
|
|
/>
|
|
<label className="form-check-label" htmlFor={key + variant}>
|
|
{variant}
|
|
</label>
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
}
|
|
|
|
export function RadioWrapper(target, id, data, {title, variants, outvar, fallback, icon, tip}) {
|
|
return <Radio target={target} title={title} variants={variants} outvar={outvar} icon={icon} tip={tip} key={id}
|
|
fallback={fallback}
|
|
id={id} data={data}/>;
|
|
} |