White Whale
White Whale

Reputation: 39

Why can I not call function in react js

Why can I not write a function and call a function using button in react.js? In this code, I want click button, an alert pop up and say that survey has submitted. How can i do it ?

function finish(){
    alert('Survey Submitted! Thank you');    

}

function Task3(){


    return(
        <div className="head">
          <h1>Experiment</h1>
          <h3>Task 3</h3>
          <p>In Task 3, you will see the right answer of your guess. </p>
          <div className="video">
          <div> <MultiStep steps={steps}/> </div>

          </div>
         <button className="task3-finish" onSubmit = {finish} >Finish Thanks!</button>

          </div>

    )



}

export default Task3

Upvotes: 1

Views: 880

Answers (3)

Viraj
Viraj

Reputation: 666

you need to pass that new function as a prop. then you can call the new function.

your functional component can look like this. (i commented some codes and changed onsubmit as onclik)

Task3.js

    import React from "react";

function Task3(props) {
  return (
    <div className="head">
      <h1>Experiment</h1>
      <h3>Task 3</h3>
      <p>In Task 3, you will see the right answer of your guess. </p>
      <div className="video">
        {/* <div>
          {" "}
          <MultiStep steps={steps} />{" "}
        </div> */}
      </div>
      <button className="task3-finish" onClick={props.callTask3Prop}>
        Finish Thanks!
      </button>
    </div>
  );
}

export default Task3;

App.js

import React, { Component } from "react";
import Task3 from "./Task3";

class App extends Component {
  callTask3() {
    alert("Task3 call...");
  }

  render() {
    return (
      <div className="App">
        <Task3 callTask3Prop={this.callTask3} />
      </div>
    );
  }
}

export default App;

i have added a working example here, example

Upvotes: 0

Jasper
Jasper

Reputation: 56


function Task3(){

finish(){
    alert('Survey Submitted! Thank you');    

}

    return(
        <div className="head">
          <h1>Experiment</h1>
          <h3>Task 3</h3>
          <p>In Task 3, you will see the right answer of your guess. </p>
          <div className="video">
          <div> <MultiStep steps={steps}/> </div>

          </div>
         <button className="task3-finish" type="button" value="Submit" onClick= {this.finish} >Finish Thanks!</button>

          </div>);



}

export default Task3

I think this could help.

Upvotes: 0

Afia
Afia

Reputation: 683

Did you mean to use onClick? because onSubmit should be used on the <form> element.

<form onSubmit = {() => finish() }> 
</form>

<button onClick = {() => finish() }> 
</button>

Upvotes: 3

Related Questions