Reputation: 25
I m a beginner in React please can someone help in this I wrote this function :
import React, {
Component }
from 'react';
import './Grid.css';
import test from "../product.json";
import $ from 'jquery';
class Grid extends Component {
makeGrid = () =>{
var data = test.map( x => [ x.name, x.price, ] );
$( document ).ready(function() {
console.log( "ready!" );
$('.boxes').append('<div className = "boxi"> Success </div>')
});
I want to execute this function so i tried :
render() {
return (
<div className = "Grid" >
< section className = "boxes" >
< /section> < /div > );
<h2> {this.makeGrid}</h2>
}
}
export default Grid;
but nothing happen even the console.log does not work . Please can someone help me .
Upvotes: 0
Views: 111
Reputation: 12181
Here you go with a solution
import React, { Component } from 'react';
import './Grid.css';
import test from "../product.json";
import $ from 'jquery';
class Grid extends Component {
constructor(props) {
this.makeGrid = this.makeGrid.bind(this);
}
makeGrid = () => {
var data = test.map( x => [ x.name, x.price, ] );
console.log( "ready!" );
$('.boxes').append('<div className = "boxi"> Success </div>')
}
render() {
return (
<div className="Grid">
<section className="boxes">
</section>
< /div >
<h2>
{this.makeGrid()}
</h2>
);
}
}
export default Grid;
You need to bind this
to the makeGrid method.
Upvotes: 0
Reputation: 4928
Two problems i noticed. This is not a react thing. Its a javaScript . this.makeGrid
calls your function definition , but it doesn't execute it. To execute it, you need the opening and closing brackets. So basically
makeGrid = () =>{
}
and
<h2> {this.makeGrid}</h2>
Should render the function string. However.
<h2> {this.makeGrid()}</h2>
Should execute your function in JavaScript.
The second problem i am suspecting, makeGrid
is a function in the class. It isn't necessarily recognized by this
being the class itself. So
<h2> {this.makeGrid.bind(this)}</h2>
Might be the right way thing to do.
Update
Move your method execution to componentDidMount
lifecyle of react. so add this.
componentDidMount() {
this.makeGrid()
}
remove <h2> {this.makeGrid()}</h2>
from render method. Study about componentDidMount
Here You don't need to call your method in render like that. You shouldn't do that.
Upvotes: 1