Ruben Pauwels
Ruben Pauwels

Reputation: 380

Onclick component setState() of main component

I am trying to set the state (of MainDevicePicker) with the current Devicename onClick of the Device-component.

For some reason the onClick handler is not working and my console.log() is not showing.

MainDevicePicker.js

import React, { Component } from 'react';

import Device from '../Device/Device';
import './MainDevicePicker.css';

class MainDevicePicker extends Component {
  constructor(){
    super();
    this.selectSubDevice = this.selectSubDevice.bind(this);
    this.state = {
      device: '',
    };
  }

  selectSubDevice(e){
    e.preventDefault();
    console.log('TEST');
    this.setState({
      device: this.props.name,
    })
  }

  render() {
    return (
        <div className="MainDevicePicker">
          <Device name="Mac" fa="apple" onClick={this.selectSubDevice}/>
          <Device name="iPad" fa="apple"/>
          <Device name="iPhone" fa="apple"/>
          <Device name="Laptop" fa="windows"/>
          <Device name="Display" fa="desktop"/>
        </div>
    );
  }
}

export default MainDevicePicker;

Device.js

import React, {Component} from 'react';
import FontAwesome from 'react-fontawesome';
import './Device.css';

class Device extends Component {
  render() {
    return (
        <div className="Device">
          <FontAwesome className='DeviceLogo' name={this.props.fa} />
          <p className="DeviceName">{this.props.name}</p>
        </div>
    );
  }
}

export default Device;

Upvotes: 0

Views: 272

Answers (2)

user2073973
user2073973

Reputation: 584

I think you can't set an onClick event on a react component. You have to accept the "onClick" as a prop in the Device class, and pass it through to your div like:

<div className="Device" onClick={this.props.onClick}>

See the following example: https://pastebin.com/5Dyf1zXC

Upvotes: 0

Przemek eS
Przemek eS

Reputation: 1304

You must bind element to fire this as example:

<Device name="Mac" fa="apple" onClick={this.selectSubDevice.bind(this}/>

on Device :

 return (
    <div className="Device" onClick={this.props.onClick}>
      <FontAwesome className='DeviceLogo' name={this.props.fa} />
      <p className="DeviceName">{this.props.name}</p>
    </div>
);

Upvotes: 1

Related Questions