I am facing a few issues. I will be glad and thankful if someone help.
In the first one, when I click on the button to show options array which I get through props from the parent component. It shows options.map is not a function. But, in concole.log() this.state.options get filled with props through button click. What I need is button is shown but when I click it disappears and the only list of the array is shown.
import React, { Component } from 'react';
class DoctorSelectTiming extends Component {
state = {
options: [],
isLoading: false
}
selectTiming = (props) => {
const setItems = this.state.options.push(...this.props.props);
this.setState({options: setItems, isLoading: true});
console.log(this.state.options );
}
render() {
const {isLoading, options } = this.state;
return (
<div>
{!isLoading ? <button onClick={this.selectTiming}>Select Timing</button> : (options.map(option => <li>{option}</li>))
}
</div>
)
}
}
export default DoctorSelectTiming;
Do this instead in your selectTiming
function:
selectTiming = () => {
// set the loading to true first and setting it to false afterwards.
this.setState({ isLoading: true });
const newItems = [...this.props.props];
this.setState({ options: newItems, isLoading: false });
}
You are assigning this.state.options.push(...this.props.props)
, which in theory, returns ONLY the length of the array after the element was pushed in the array.
This is an example code of what you did:
const arr = [1,2,3,4]
console.log(arr) // [1,2,3,4]
const anotherArr = []
const newArr = anotherArr.push(arr) // assigning it to newArr will only return the length
// of the array after it was pushed.
console.log(newArr) // 4
So, the better approach would be assigning setItems with the actual value of this.props.props
instead of directly modifying the actual state, which is a BAD practice. Also, the argument props
is unnecessary since props is already available locally in your component.