How can i pass props from a functional button component to another function component that displays the prop?

2.6k views Asked by At

I am trying to create a functional component button component that changes state once clicked, and depending on clicked/not clicked - another component (Content) will render. How do I achieve this by passing props? I get an in Button.jsx that setState is not a function.

        function App() {
      return (
        <div>
          <Parent />
        </div>
      );
    }
    export default App;


            import React, { useState } from 'react';
        import { Content } from './Content';
        import { Button } from './Button';
        export const Parent = () => {
            const [state, setState] = useState(false);

            return (
                <div>
                    <Button state={state} setStat={setState} />
                    {state && <Content />}
                </div>
            );
        };



            export const Button = ({ state, setState }) => {
            const handler = () => setState(!state);
            return (
                <div>
                    <button onClick={handler}>{state ? 'Clicked' : 'Click me'}</button>
                </div>
            );
        };



            export const Content = () => {
            return <div>Show this when button is clicked and Parent state is true</div>;
        };
1

There are 1 answers

0
ike On
  1. it's hard to tell without knowing the relationship between ButtonLatest and DisplayLatest.

  2. if they are both descendants of the same parent (i.e. they have a common ancestor), then that state could live in that common ancestor. (the setState function could be passed down to ButtonLatest as a prop.

there are a few ways to do what you're after, but it depends on their relationship; a Codepen would help here.

const CommonParent = () => {
   const [isSelected, setIsSelected] = useState(false)
   
   return <div>
             { isSelected && <DisplayLatest /> }
             <ButtonLatest 
                 isSelected={isSelected} 
                 setIsSelected={setIsSelected}
              />
          </div>
   }

const ButtonLatest = ({setIsSelected, isSelected}) => {

    return (
        <div>
            <button onClick={ () => setIsSelected(!isSelected) }>
               { isSelected ? 'Clicked' : 'Click me'}
            </button>
        </div>
);