0

Is this code syntactically correct? The effect I'm trying to achieve is for the text to appear once the button has been clicked...

import React, { useState } from 'react';
import './App.css';

function Example(){
  const [state, setState] = useState({shows: false});

  return(
    <div>{state.shows && <p>hi</p>}
      <button onClick={() => setState({shows: true})}>
        Click me
      </button>
    </div>
  )
}

export default Example;

4
  • 1
    Sure, but for simple state it is usually better to name the state object for what it holds, i.e. shows and setShows, and give the initial value directly, i.e. useState(false). Your render then would be <div>{shows && <p>... For more complex state and mutations useReducer is recommended. Commented Oct 6, 2019 at 23:12
  • Determining if code is syntactically correct is pretty easy--see if it makes it past the parser. Maybe you meant something different. Commented Oct 6, 2019 at 23:17
  • @DrewReese Thats a good way to make it simpler...but Jiml made it apparent that I didn't have to change the conts. Commented Oct 6, 2019 at 23:24
  • @user12099646, true, be that as it may, but when you start creating or working with functional components with several state hooks you'll appreciate having meaningful variable names. Commented Oct 6, 2019 at 23:54

2 Answers 2

1

Yes, but you don't need using object

function Example(){
 const [state, setState] = useState(false);

 return(
  <div>{state && <p>hi</p>}
   <button onClick={() => setState(true)}>
     Click me
   </button>
  </div>
 )
}
Sign up to request clarification or add additional context in comments.

Comments

0

Yes, what you have implemented is fine.

But, Hooks are used to simplify the use of react state.

Hence, in your case, writing in the below format would considered as perfect

const [shows, updateShow] = useState(false);
<button onClick={() => updateShow(!shows)}>Click me</button>

Ref: https://reactjs.org/docs/hooks-state.html

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.