Reputation:
I mean like this so that the hook can be used like this <Foo id="foo1" />
and <Foo id="foo2" />
export const Foo = () => {
const [state + props.id, state + props.id] = useState("foo")
return (
<div>
</div>
)
}
Upvotes: 0
Views: 578
Reputation: 171669
You are looking at this wrong. Each instance of a component has it's own state.
What you aren't doing is setting the props
argument in the Foo function so you can work with it inside the functional component
const { useState } = React;
const Foo = ({id}) => {
// ^^ destructured props argument
const [myVar, setMyvar] = useState(id)
return (
<div className="foo">
From useState: {myVar}
<hr/>
Or from props: {id}
</div>
)
}
ReactDOM.render(
<div>
<Foo id="foo 1"/>
<Foo id="foo 2"/>
</div>,
document.getElementById("root")
);
.foo {border: 2px solid #ccc; margin: 1em; padding:1em}
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
Upvotes: 1
Reputation: 1670
If I understand correctly there is no need to create other variable names. You only use these names inside the component. So the state of one component instance will not affect the other instance.
export const Foo = () => {
const [state, setState] = useState("foo")
return (
<div>
</div>
)
}
Upvotes: 0