TypeError: Cannot read property 'onMouse' of undefined React Class Component

37 Views Asked by At

I want to do when the user clicks on Input Element and the button element in the form will change to Send icon from the microphone icon. My idea was to get the value from onClick or mouseEnter handler and pass it through the if-else statement and set the correct icon

Here is my Code `

import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form';
import InsertEmoticonIcon from '@material-ui/icons/InsertEmoticon';
import AttachFileIcon from '@material-ui/icons/AttachFile';
import MicIcon from '@material-ui/icons/Mic';
import SendIcon from '@material-ui/icons/Send';

import styled from 'styled-components'
import './MessageSender.css'

export class MessageSender extends Component {

constructor(props){
    super(props);
    this.state = {
        bool: 'false'
    }
    this.onMouse = this.onMouse.bind(this);
}


onMouse(){
    this.setState({bool: "true"})
}

renderInput(formProps){
    
    return <input 
        onChange={formProps.input.onChange}
        value={formProps.input.value}
        placeholder="Message" 
        onClick={this.onMouse()}
    />
}

onSubmit(formValues){
    console.log(formValues);
}
check(){
    // return <Send />
    if(this.state.bool === 'true'){
        return <Send />
    }else{
        return <Mic />
    }
}

render() {
    return (
            <form autoComplete="off" onSubmit={this.props.handleSubmit(this.onSubmit)}>
                <Emotion />
                <Field  name="Message" component={this.renderInput} placeholder="Message"  />
                <Attach />
                <button>
                    {this.check()}
                </button>
            </form>
        
    )
}
}

const Emotion = styled(InsertEmoticonIcon)`
    width: 40px!important;
    height: 40px!important;
    color: rgb(170,170,170);
`

const Attach = styled(AttachFileIcon)`
    width: 40px!important;
    height: 40px!important;
    color: rgb(170,170,170);
    margin-right: 0.3rem;
`
const Mic = styled(MicIcon)`

`
const Send = styled(SendIcon)`

`

export default  reduxForm({
    form: 'message'
})(MessageSender);

`

Therefore, here is my Error

Help me please, thanks!

1

There are 1 best solutions below

0
Ace On

Try this out. I think using an arrow function will solve an issue with using this. And you shouldn't be calling the function when you pass it to onClick

renderInput = (formProps) => {
    
    return <input 
        onChange={formProps.input.onChange}
        value={formProps.input.value}
        placeholder="Message" 
        onClick={this.onMouse}
    />
}