Reputation: 131
I have the following react component:
class RenderChart extends Component {
constructor(props){
super(props);
this.selectValue=this.selectValue.bind(this);
this.selectValueYear1=this.selectValueYear1.bind(this)
this.state={
isLoaded:false,
items_y1: [],
items_y2: [],
items_y12: [],
arr_keys:[],
arr_vals:[],
selectValue2:"",
selectVal:"",
data:[],
}
}
selectValueYear1(e){
this.setState({
selectVal:e.value
})
}
selectValue (e) {
var selectVal=this.state.selectVal;
fetch("http://127.0.0.1:8000/api/values/"+selectVal+"/"+e.value)
.then(response => response.json())
.then(json => {
this.setState({
items_y1:json.commontopics,
isLoaded:true
})
});
};
render() {
var {isLoaded,desc,selectValue2,selectVal,items_y1} = this.state;
const data = [
{
value: "2011",
label: "2011"
},
{
value: "2012",
label: "2012"
},
{
value: "2013",
label: "2013"
},
{
value: "2014",
label: "2014"
},
{
value: "2015",
label: "2015"
},
{
value: "2016",
label: "2016"
},
{
value: "2017",
label: "2017"
},
{
value: "2018",
label: "2018"
},
{
value: "2019",
label: "2019"
},
{
value: "2020",
label: "2020"
}
];
if(isLoaded){
return (
<>
<br></br>
<React.Fragment>
<Row>
<Col>
<Label>Select an Year</Label>
<Select placeholder="Select Option" options={data} value={data.find(obj => obj.value === selectVal)}
onChange={this.selectValueYear1}
/>
</Col>
<Col>
<Label>Select an Year</Label>
<Select placeholder="Select Option" options={data} value={data.find(obj => obj.value === selectValue2)}
onChange={this.selectValue}/>
</Col>
</Row>
<br></br>
<br></br>
<Row>
{console.log("items",items_y1)}
<img src={`data:image/png;base64,${items_y1}`}></img>
</Row>
</React.Fragment>
</>
);
}
else{
return (
<>
<Row>
<Col>
<Label>Select an Year</Label>
<Select placeholder="Select Option" options={data} value={data.find(obj => obj.value === selectVal)}
onChange={this.selectValueYear1}
/>
</Col>
<Col>
<Label>Select an Year</Label>
<Select placeholder="Select Option" options={data} value={data.find(obj => obj.value === selectValue2)}
onChange={this.selectValue}/>
</Col>
</Row>
</>
)
}
}
}
export default RenderChart ;
I have two dropdowns to select values from.When I select a value from second dropdown,image is rendered and page is refreshed.I don't understand why page is being refreshed.Also,this is a component inside another component.and there are many other child components
Upvotes: 0
Views: 1675
Reputation: 550
Try adding e.preventDefault() in your function
selectValue (e) {
e.preventDefault()
var selectVal=this.state.selectVal;
fetch("http://127.0.0.1:8000/api/values/"+selectVal+"/"+e.value)
.then(response => response.json())
.then(json => {
this.setState({
items_y1:json.commontopics,
isLoaded:true
})
});
};
Upvotes: 1