Denis
Denis

Reputation: 7343

React inline logic in render()

I just wonder how apply inline templates logic in React. I mean in case when I need change class of element how to do that easily?

class RegisterForm extends Component {
    ...
    render() {
        let email = this.state.email.error; //true or false
        return (<div {email ? className="has-error" : className="regular"}></div>)
}

Then I have an error:

Syntax error: C:/project/components/signup/index.js: Unexpected token, expected ... (107:22)

How to perform that? Or it's only possible to wrap in if/else full div block only?

Upvotes: 3

Views: 1178

Answers (2)

J Livengood
J Livengood

Reputation: 2738

You could do a couple things:

<div className={email ? "has-error" : "regular"}> </div>

Or to keep it cleaner

let email = this.state.email.error;
let divClass = email ? "has-error" : "regular";

return <div className={divClass}> </div>

Upvotes: 5

Mayank Shukla
Mayank Shukla

Reputation: 104459

Assign the value conditionally not attribute. Define className attribute and assign its value on the basis of email value.

Write it like this:

<div className = { email ? "has-error" : "regular"}> </div>

Upvotes: 2

Related Questions