简体   繁体   中英

I want to show and hide a form on toggle of a radio button in React js . Im trying how to use react hooks to hide or show a component on onChange even

Now i have used state hook to hide the Form when the page loads. And upon the click or toggle of the radio I'm able to show the Form, But if i toggle the radio again, the form is not hiding.

This is what i have implemented:

const WelcomeTab = () => {
  const [toggle, settoggle] = useState(false);

  return (
    <React.Fragment>
      <Tab.Pane
        style={{
          borderRadius: '7px',
          padding: '30px',
        }}
        attached={false}
      >
        <Grid>
          <Grid.Row>
            <Grid.Column floated="left" width={8}>
              <Header
                style={{
                  fontSize: '18px',
                  fontFamily: 'Nunito-Regular',
                  color: '#4F4F4F',
                }}
              >
                Welcome Screen
              </Header>
            </Grid.Column>
            <Grid.Column floated="right" width={4}>
              <Header
                as="h4"
                style={{
                  display: 'flex',
                  justifyContent: 'space-around',
                  marginLeft: '30px',
                }}
              >
                Customize
                <Radio toggle onChange={() => settoggle({ toggle: !toggle })} />
              </Header>
            </Grid.Column>
          </Grid.Row>
        </Grid>

        {toggle ? (
          <Form style={{ paddingTop: '20px' }}>
            <Form.Field>
              <label style={lableStyle}>Title</label>
              <input style={{ marginBottom: '20px' }} />
              <label style={lableStyle}>Message</label>
              <TextArea />
            </Form.Field>
          </Form>
        ) : null}
      </Tab.Pane>
    </React.Fragment>
  );
};

const lableStyle = {
  fontFamily: 'Nunito-Regular',
  fontWeight: 400,
  color: '#4F4F4F',
  fontSize: '15px',
  display: 'inline-block',
  marginBottom: '10px',
};
export default WelcomeTab;

try to add useEffect hook along with change like below, you no longer need to {} this is old syntax of setState, using hooks we directly make the changes, hope this helps

useEffect(()=>{},[toggle]) 

replace this wrong syntax code, i can see its not json its boolean value

<Radio toggle onChange={()=>settoggle({toggle: !toggle})}/>

as this is old syntax not work with hooks, try to implment this instead,

<Radio toggle onChange={()=>settoggle(!toggle)}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM