Hirschzd01
Hirschzd01

Reputation: 31

I'm trying to render a input form with an onClick listener in react, but it isn't working

I'm trying to build a component that is initially just a button, but when clicked the component will render a input form by toggling a value in state from false to true. I keep getting the error: ./src/Components/CreateButton.js Line 29: 'inputForm' is not defined no-undef

import React, {Component} from "react"
import App from "../App"

export default class CreateButton extends Component{
constructor(){
    super()
    this.state={
        name:"",
        imageUrl:"",
        rating:"",
        showForm: false
    }
    this.renderCreateForm=this.renderCreateForm.bind(this)
}
toggleFormView(){
    this.setState({showForm:true})
}

render(){
    {const inputForm = (<div>
        <input placeholder="Enter a name: " onChange={(e) => this.setState({name:e.target.value})}></input>
        <input placeholder="Enter a image Url : " onChange={(e) => this.setState({imageUrl:e.target.value})}></input>
        <input placeholder="Enter a rating: " onChange={(e) => this.setState({rating:e.target.value})}></input>
        <button onClick={this.props.createPostFn(this.state.name,this.state.imageUrl,this.state.rating)}>Submit</button>
    </div>)}
    return(
        <div>
            <button onClick={()=>this.toggleFormView()}>Submit a new business: </button>
            {this.state.showForm? inputForm:null};
        </div>
    )
}
}

Upvotes: 0

Views: 58

Answers (2)

BenoitVasseur
BenoitVasseur

Reputation: 782

Jasmshid's answer fixes your issue. See here : https://codesandbox.io/s/1qj00r237q

Be aware that curly braces {/* JS code */} around js code are only needed in JSX expressions : https://reactjs.org/docs/introducing-jsx.html

<div>{/* because I am in a JSX expression I need curly braces */}</div>.

Upvotes: 1

Jay
Jay

Reputation: 841

Remove the curly braces outside the variable definition:

render(){
    const inputForm = (<div>
        <input placeholder="Enter a name: " onChange={(e) => this.setState({name:e.target.value})}></input>
        <input placeholder="Enter a image Url : " onChange={(e) => this.setState({imageUrl:e.target.value})}></input>
        <input placeholder="Enter a rating: " onChange={(e) => this.setState({rating:e.target.value})}></input>
        <button onClick={this.props.createPostFn(this.state.name,this.state.imageUrl,this.state.rating)}>Submit</button>
    </div>)
    return(
        <div>
            <button onClick={()=>this.toggleFormView()}>Submit a new business: </button>
            {this.state.showForm? inputForm:null};
        </div>
    )
}

Upvotes: 1

Related Questions