Dileet Dileet - 1 month ago 15
Javascript Question

Calling a function from a different react file

I'm close to getting this to work. Hoping someone can help me with this.

I have 2 React files. One being the

Container
and the other being the
Nav
component.

Inside my container component which is called
_template.js
, I'm importing a modal npm package. I created a
showModal
function inside this container file that I'm trying to access inside the
Nav
component.

This is what I have so far and receive this error
Uncaught TypeError: Cannot read property 'modal' of undefined


_template.js:

import React from 'react';
import { Link } from 'react-router';


import { prefixLink } from 'gatsby-helpers';
import { config } from 'config';

import Headroom from 'react-headroom';

import Nav from './nav.js';

import '../css/main.scss';

import Modal from 'boron/DropModal';

const modalStyle = {
minHeight: '500px',
backgroundColor: '#303841'
};

const backdropStyle = {
backgroundColor: '#F6C90E'
};

const contentStyle = {
backgroundColor: '#303841',
padding: '3rem'
};





export default class RootTemplate extends React.Component {
static propTypes = {
location: React.PropTypes.object.isRequired,
children: React.PropTypes.object.isRequired,
}

static contextTypes = {
router: React.PropTypes.object.isRequired,
}

constructor() {
super();

}

showModal () {
this.refs.modal.show();
}



render() {
return (
<div>
<Headroom>
<Nav showModal={this.showModal}/>
</Headroom>
<Modal ref="modal" modalStyle={modalStyle} contentStyle={contentStyle} backdropStyle={backdropStyle}>
<form>
<label>Name:</label>
<input type="text"/>
<label>Email:</label>
<input type="email"/>
<label>Message:</label>
<input type="text-area"/>
<input type="submit" placeholder="Submit" />
</form>
</Modal>
{this.props.children}
</div>
);
}
}


And my Nav.js file:

import React from 'react';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers';



import { Nav, NavGroup, NavItem, NavToggle, Icon } from 're-bulma';



export default class nav extends React.Component {
static propTypes = {
name: React.PropTypes.string,
};

constructor(props) {
super(props);
}



render() {
return (
<div>
<Nav>
<NavGroup align="left">
<NavItem>
<Link to={prefixLink('/')}>
<h2>Dillon Raphael</h2>
</Link>
</NavItem>
</NavGroup>

<NavToggle />

<NavGroup align="right" isMenu>
<NavItem>
</NavItem>
<NavItem>
</NavItem>
<NavItem>
<a href="#" onClick={::this.props.showModal}>Let's Work!</a>
</NavItem>
</NavGroup>
</Nav>



</div>
);
}
}


Notice the
<a href="#" onClick={::this.props.showModal}>Let's Work!</a>
this is where I'm trying to call the showModal function that I pass down from the
_template.js
file.

Answer

Add to your constructor, in _template.js file this code:

this.showModal = this.showModal.bind(this);

The constructor then should look like this:

constructor(props) {
super(props);
this.showModal = this.showModal.bind(this);
}