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>;
};
it's hard to tell without knowing the relationship between
ButtonLatest
andDisplayLatest
.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 toButtonLatest
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.