nirmal
nirmal

Reputation: 2180

clicking first element in loop of react js

What I want to do if user clicks on element then add a class on element and also, I have below repeat code, where I want to trigger click on first element of loop when components get loaded or either add class.

Whichever is feasible.

Object.keys(this.state.cdata).map((id,val) => {
    return (
        <div key={val}  onClick={this.select.bind(this, this.state.cdata[id].id)} >
            <div><i className="fa fa-globe" aria-hidden="true"></i> 
                <div className="country-name">{this.state.cdata[id].name}</div>
                <input type="text" value={this.state.cdata[id].name} className="hidden"  onChange={this.edit}   onKeyPress={this.check}/>
            </div>
        </div>
    )
})

Upvotes: 0

Views: 813

Answers (1)

Aswin Ramesh
Aswin Ramesh

Reputation: 1674

I think you can use componentDidMount for this like:

componentDidMount() {
    this.setState({ loaded: 'newClass' });
}

and in your code just add the class by checking the index

Object.keys(this.state.cdata).map((id,val) => {
    return (
        <div key={val} className={val === 0 && this.state.loaded} onClick={this.select.bind(this, this.state.cdata[id].id)} >
            <div><i className="fa fa-globe" aria-hidden="true"></i> 
                <div className="country-name">{this.state.cdata[id].name}</div>
                <input type="text" value={this.state.cdata[id].name} className="hidden"  onChange={this.edit}   onKeyPress={this.check}/>
            </div>
        </div>
    )
})

Upvotes: 1

Related Questions