0

I have some variables that are set within a function in one component of my react application that I need to reuse in other components.

I set the variables in component 1 like so (this is a much simplified version but captures the structure)

    export default function Example() {
                const [market, setMarket] = useState('');
        return ( 
<button onClick={setMarket('1')}>Click 1</button>
    <button onClick={setMarket('2')}>Click 2</button>
    <button onClick={setMarket('3')}>Click 3</button> )}

How can I export the 'market' variable specifically, so that I can import it into another component (in a separate jsx file) and render as necessary. I know that I can just import the whole component, or set a variable outside of this function in component 1 and export it but I do not know how I would then conditionally set it based on which button is clicked.

Thank you

1 Answer 1

1

Hey @Milo there are different ways to use state value in another component.

  1. First is props- Create a component that passes values like-

    const passValue = () => { const [ value, setValue ] = useState("") return (

    ) }

While in the second component we get the value like-

const SecondComponent = ({value})=>{
return(
<div>
{value}
</div>
)
}
  1. While Second method is to pass value using state and get it by useLocation in another component-

First Component like-

const FirstComponent = () =>{
return(
<div>
<Link to="/secondpage" state={{value:yourValue/state}}>Click Here</Link>
</div>
)
}

Second Component Like-

const Second Component = () => {
const {state} = useLocation()
return(
<div>{state}</div>
)
}

Hope these solution helps to solve your problem. If you still facing issue lemme know, i will help you. Thanks

Sign up to request clarification or add additional context in comments.

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.