1

So I'm trying to render some JSX when a user presses a button, I'm trying to do this via onClick but it is not working, The JSX does not get rendered on the screen. Is there a way to do this? My code is like this:

function RandomScreen() {
    async function HandleClick() {
        // make API post request
        .then(function(response) {
            return (<h1>{response.data}</h1>)
        })
    }
    return (
        <button onClick={HandleClick}>Click me</button>
    )
}
2
  • 1
    Returning jsx from the function would not work, it needs to be part of the return block. Are you trying to show the text above/below the button? Commented Apr 24, 2021 at 9:18
  • Below the button, Can I possibly return a whole screen? It would be better if button was not there after the user pressed it. @ksankar Commented Apr 24, 2021 at 9:21

2 Answers 2

2

I think you are looking for something like this:

function RandomScreen() {
  const [data, setData] = useState(null);
  async function HandleClick() {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);

        setData(json);
      });
  }
  return (
    <button onClick={HandleClick}>
      Click me
      {data && <h1>{JSON.stringify(data, null, 2)}</h1>}
    </button>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

store your data in a state for example

const [data, setData] = React.useState();


...
.then(function(response) {
    setData(response.data);
 })

and in JSX you can handle the display part:

{data && <h1>{data}</h1>}

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.