Sunday, 25 August 2019

React - change this.state onClick rendered with array.map()

Im new to React and Javascript, so sorry if this is too basic.

I have a Menu component which renders an animation onClick and then redirects the app to another route, /coffee.

I would like to pass the value which was clicked (selected) to function this.gotoCoffee and update this.state.select, but I don't know how, since I am mapping all items in this.state.coffees in the same onClick event.

How do I do this and update this.state.select to the clicked value?

My code:

class Menus extends Component{
  constructor (props) {
    super(props);
    this.state = { 
        coffees:[],
        select: '',      
        isLoading: false,
        redirect: false
    };
  };
  gotoCoffee = () => {
    this.setState({isLoading:true})
    setTimeout(()=>{
      this.setState({isLoading:false,redirect:true})
    },5000)
  }

  renderCoffee = () => {
    if (this.state.redirect) {
      return (<Redirect to={`/coffee/${this.state.select}`} />)
    }
  }

  render(){
    const data = this.state.coffees;

    return (
      <div>
        <h1 className="title is-1"><font color="#C86428">Menu</font></h1>
        <hr/><br/>
        {data.map(c => 
          <span key={c}>
            <div>
               {this.state.isLoading && <Brewing />}
               {this.renderCoffee()}
              <div onClick={() => this.gotoCoffee()} 
                  <strong><font color="#C86428">{c}</font></strong></div>
            </div>
          </span>)
        }
      </div>
    );
  }
}

export default withRouter(Menus);


I have tried passing the value like so:

  gotoCoffee = (e) => {
    this.setState({isLoading:true,select:e})
    setTimeout(()=>{
      this.setState({isLoading:false,redirect:true})
    },5000) 
    console.log(this.state.select)
  }

an like so:

<div onClick={(c) => this.gotoCoffee(c)} 

or so:

<div onClick={(event => this.gotoCoffee(event.target.value} 

but console.log(this.state.select) shows me 'undefined' for both tries.

It appears that I'm passing the Class with 'c'.

browser shows me precisely that on the uri at redirect:

http://localhost/coffee/[object%20Object]


Now if I pass mapped 'c' to {this.renderCoffee(c)}, which not an onClick event, I manage to pass the array items.

but I need to pass not the object, but the clicked value 'c' to this.gotoCoffee(c), and THEN update this.state.select.

how do I fix this?



from React - change this.state onClick rendered with array.map()

No comments:

Post a Comment