1

im trying to pass a string to a function using onClick method, here is my code :

App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

const todos = [
{id: 1, nama: 'belajar', status: 'selesai'},
{id: 2, nama: 'makan', status: 'belum selesai'}
]

export class MyTodos extends React.Component{
  constructor(){
    super();
    this.sayHello = this.sayHello.bind(this);
  }
}

function sayHello(name) {
  alert(`hello, ${this.name}`);
}

function App() {
  return (
    <div className="App">
      <div className="Navbar">
        <nav className="navbar navbar-dark bg-dark rounded-pill col-sm-8">  
          <input type="text" className="form-control form-control-sm col-sm-6 rounded-pill" name="aktivitas"></input>
          <button className="btn form-control form-control-sm col-sm-4 bg-light rounded-pill" onClick={() => sayHello(this.aktivitas)}>
            Tambah
          </button>
        </nav>
      </div>
      <br></br><br></br>
      <div className="Kartu card">
        <ul className="list-group list-group-flush"> 
              {todos.map(todos => <li className="list-group-item">{todos.nama} : {todos.status}</li>)}
        </ul>
      </div>
    </div>
  );
}




export default App;

the expected output is, when i type something inside the input field it will give me an alert that says Hello, <inputted string> For example if i type name inside the input field it will gave me hello, name

i guess it have something to do with binding something, i tried to bind it bit it gave me this error : TypeError: Cannot read property 'aktivitas' of undefined

thanks before, any help will be appreciated

3 Answers 3

1

Please try this:

<button className="btn form-control form-control-sm col-sm-4 bg-light rounded-pill" onClick={(e) => {
     this.sayHello(e, this.aktivitas)
}}>Tambah</button>

The function body should be:

sayHello = (event, aktivitas) => {
     console.log(aktivitas);
};
Sign up to request clarification or add additional context in comments.

2 Comments

i still got the same error, here is the error TypeError: Cannot read property 'sayHello' of undefined
@LuthfiMusafa, I have updated my answer. as you are using class component so we have to use arrow function. Please check sayHello function
0

Try code bellow.

import React from 'react';
import logo from './logo.svg';
import './App.css';

const todos = [
{id: 1, nama: 'belajar', status: 'selesai'},
{id: 2, nama: 'makan', status: 'belum selesai'}
]

function App() {
  const [name, setName] = React.useState('');
  const handleOnChange = React.useCallback((event) => {
    const { target: { value } } = event;
    
    setName(value);
  }, []);

  const sayHello = React.useCallback(() => {
    alert(`hello, ${name}`);
  }, [name]);

  return (
    <div className="App">
      <div className="Navbar">
        <nav className="navbar navbar-dark bg-dark rounded-pill col-sm-8">  
          <input
            type="text"
            className="form-control form-control-sm col-sm-6 rounded-pill"
            name="aktivitas"
            value={name}
            onChange={handleOnChange}
          />
          <button
            className="btn form-control form-control-sm col-sm-4 bg-light rounded-pill"
            onClick={sayHello}
          >
            Tambah
          </button>
        </nav>
      </div>
      <br></br><br></br>
      <div className="Kartu card">
        <ul className="list-group list-group-flush"> 
              {todos.map(todos => <li className="list-group-item">{todos.nama} : {todos.status}</li>)}
        </ul>
      </div>
    </div>
  );
}

Comments

0

try this code, you need onChange on your input tag:

import React from 'react';
import logo from './logo.svg';
import './App.css';

const todos = [
{id: 1, nama: 'belajar', status: 'selesai'},
{id: 2, nama: 'makan', status: 'belum selesai'}
]

class MyTodos extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      aktivitas: '',
    };

    this.sayHello = this.sayHello.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }


    handleChange(e){
        this.setState({ aktivitas: e.target.value });
    }

    sayHello(){
        console.log(this.state.aktivitas);
    }


    render() {
      return (
        <div className="App">
          <div className="Navbar">
            <nav className="navbar navbar-dark bg-dark rounded-pill col-sm-8">  
              <input type="text" className="form-control form-control-sm col-sm-6 rounded-pill" name="aktivitas" onChange={ this.handleChange }></input>
              <button className="btn form-control form-control-sm col-sm-4 bg-light rounded-pill" onClick={ this.sayHello }>Tambah</button>
            </nav>
          </div>
          <br></br><br></br>
          <div className="Kartu card">
            <ul className="list-group list-group-flush"> 
                  {todos.map(todos => <li className="list-group-item">{todos.nama} : {todos.status}</li>)}
            </ul>
          </div>
        </div>
      );
    }

}



export default MyTodos;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.