0

I have two questions.

① How can if statement adapt to below when the initial value of useState is true and false?

const [ goodbotton, setGoodBotton ] = useState(<Image source={require('../../images/good_botton_inactive.png')} style={ {width: 65, height: 65} }/>);

Like for Example ..

const [ goodbotton, setGoodBotton ] = useState(<Image movie?.is_my_good ? source={require('../../images/good_botton_inactive.png')} style={ {width: 65, height: 65} } : source={require('../../images/not_good_botton_inactive.png')} style={ {width: 65, height: 65} } />);

② How can setGoodBotton from React hooks and if statement adapt to below when the if statement is true and false?

<TouchableOpacity
      onPress={() => {
        if (movie.is_my_good) {
          postGood(movie.id, false)
        } else {
          postGood(movie.id, true)
        }}>
      <View style={[commonStyles.shadow]} > {/*here!!!!*/}
      </View>
</TouchableOpacity>

Like for Example ..(this is not work)

if (movie.is_my_good) {
   setGoodBotton(<View style={[commonStyles.shadow]} >)
} else {
   setGoodBotton(<View style={[uncommonStyles.shadow]} >)
}
Hinoarashi
  • 183
  • 3
  • 10
  • What is the motivation to use JSX element as a value to the state variable? Never seen such a thing, but I am pretty sure that it is a wrong use-case for the `useState` hook – Sinan Yaman Aug 10 '21 at 06:05
  • setting `jsx` in state <- this not giving you any error ?? – ME-ON1 Aug 10 '21 at 06:09
  • Yes, it is very anti-pattern to store Components/JSX into React state, instead you store data and then render that into JSX. Other than this, yes, you can use `if` statements in Javascript. – Drew Reese Aug 10 '21 at 06:09
  • please try to format your question and explanation better next time, i am having a hard time trying to understand you. You should check out `terniery` statements – Oliver Ilmjärv Aug 10 '21 at 06:14
  • Does this answer your question? [JSX: Inline conditional attribute \[href\]](https://stackoverflow.com/questions/51997751/jsx-inline-conditional-attribute-href) – Martin Aug 10 '21 at 07:24

1 Answers1

1

You're trying to render a different image conditionally, so your state is only your image.

const initialImage = movie?.is_my_good ? 'good_botton_inactive.png' : 'not_good_botton_inactive.png';
const [image, setImage] = useState(initialImage);

Then you can use your component as below

<Image source={require(`../../images/${image}`)} style={{ width:65, height:65 }} />

And you can use your condition as a function parameter.

<TouchableOpacity onPress={() => postGood(movie.id, !movie.is_my_good)}>
  <View style={[commonStyles.shadow]} />
</TouchableOpacity>

And to answer your last part of the question

const style = movie.is_my_good ? [commonStyles.shadow] : [uncommonstyles.shadow];
setGoodBotton(<View style={style} >)
Hamidreza
  • 1,360
  • 11
  • 18