I have this method render, within which I am creating a local variable category. I need to set the value of this variable inside the html in return statement using JSX.
I am using curly brackets to assign the value to the local variable, but this is not working for me. eg {category='business'}
This is what I am doing currently
export default class App extends Component {
render() {
let category = 'about';
return (
<Router>
<div>
<NavBar/>
<Switch>
<Route path="/about">
</Route>
<Route path="/business">
{category='business'}
</Route>
<Route path="/entertainment">
{category='entertainment'}
</Route>
<Route path="/general">
{category='general'}
</Route>
<Route path="/health">
{category='health'}
</Route>
<Route path="/science">
{category='science'}
</Route>
<Route path="/sports">
{category='sports'}
</Route>
</Switch>
<News pageSize={5} country="in" category={category}/>
</div>
</Router>
)
}
}
This one instead shows the category on screen.
Note : I know there are multiple ways in which I can achieve this but I wanted to know how to set local variable within my method
What you're attempting to do is to change the state of the variable. Cue React's useState and useEffect hooks (the component needs to be a functional component for hooks to work).
First import the hook:
import { useState } from 'react';
Then, in your case:
const [category, setCategory] = useState('about') // initial value
and when you need to update it:
setCategory('science') // new value