React-Native -> Couldn't change style using state












0















I've got a problem with my app. I'm trying to change style in my child component using states but unfortunately i dont get any results. I tried evrythig i know, but i dont know what is going on and why styles aren't changing at all



Here is parent :



    constructor(props) {
super(props);
this.state = {
number: 1,
cords: [

],
choosenCords: [

],
style: {flex:1,flexDirection:'row',backgroundColor:'red'}
};
}
<View style={{ marginTop: 3 }}>
<ListItem style={this.state.style} test={this.state.test} title={item.timestamp} context={item.longtitude + " " + item.latitude} click={this.getData.bind(this, item.longtitude, item.latitude, item.timestamp)} />
</View>

getData = async(x, y, z) => {

let tempTab =
tempTab.push(x)
tempTab.push(y)
tempTab.push(z)
const changeTest = this.state.test * (-1)
await this.setState({
choosenCords: [...this.state.choosenCords, tempTab],
style: {flex:1,flexDirection:'row',backgroundColor:'blue'}
})
}


}
This fragment of code represent changing style onPress. "choosenCords" are changing, but "style" don't.



Here is child:



class ListItem extends Component {
constructor(props) {
super(props);
this.state = {
test:this.props.test
};
}

render() {
return (
<View style={this.props.style}>
<Image
source={require('../Images/gps.png')}
style={{ borderWidth: 3, borderColor: '#7887AB', borderRadius: 50, marginLeft: 15, marginTop: 10 }}
/>
<View style={{ flex: 1, flexDirection: "column", marginBottom: 15, marginLeft: 10 }}>
<Text style={{ marginLeft: 10, fontSize: 16 }}>
{
"Timestamp: " + this.props.title
}
</Text>
<Text style={{ marginLeft: 15, fontSize: 15 }}>
{
"Cords:" + this.props.context
}
</Text>
</View>
<TouchableHighlight
underlayColor={'transparent'}
onPress={
this.props.click
}>
<Image
source={
require('../Images/check.png')
}
style={{ marginRight: 20 }}
/>
</TouchableHighlight>
</View>
);

}


Could someone help me with that?










share|improve this question



























    0















    I've got a problem with my app. I'm trying to change style in my child component using states but unfortunately i dont get any results. I tried evrythig i know, but i dont know what is going on and why styles aren't changing at all



    Here is parent :



        constructor(props) {
    super(props);
    this.state = {
    number: 1,
    cords: [

    ],
    choosenCords: [

    ],
    style: {flex:1,flexDirection:'row',backgroundColor:'red'}
    };
    }
    <View style={{ marginTop: 3 }}>
    <ListItem style={this.state.style} test={this.state.test} title={item.timestamp} context={item.longtitude + " " + item.latitude} click={this.getData.bind(this, item.longtitude, item.latitude, item.timestamp)} />
    </View>

    getData = async(x, y, z) => {

    let tempTab =
    tempTab.push(x)
    tempTab.push(y)
    tempTab.push(z)
    const changeTest = this.state.test * (-1)
    await this.setState({
    choosenCords: [...this.state.choosenCords, tempTab],
    style: {flex:1,flexDirection:'row',backgroundColor:'blue'}
    })
    }


    }
    This fragment of code represent changing style onPress. "choosenCords" are changing, but "style" don't.



    Here is child:



    class ListItem extends Component {
    constructor(props) {
    super(props);
    this.state = {
    test:this.props.test
    };
    }

    render() {
    return (
    <View style={this.props.style}>
    <Image
    source={require('../Images/gps.png')}
    style={{ borderWidth: 3, borderColor: '#7887AB', borderRadius: 50, marginLeft: 15, marginTop: 10 }}
    />
    <View style={{ flex: 1, flexDirection: "column", marginBottom: 15, marginLeft: 10 }}>
    <Text style={{ marginLeft: 10, fontSize: 16 }}>
    {
    "Timestamp: " + this.props.title
    }
    </Text>
    <Text style={{ marginLeft: 15, fontSize: 15 }}>
    {
    "Cords:" + this.props.context
    }
    </Text>
    </View>
    <TouchableHighlight
    underlayColor={'transparent'}
    onPress={
    this.props.click
    }>
    <Image
    source={
    require('../Images/check.png')
    }
    style={{ marginRight: 20 }}
    />
    </TouchableHighlight>
    </View>
    );

    }


    Could someone help me with that?










    share|improve this question

























      0












      0








      0








      I've got a problem with my app. I'm trying to change style in my child component using states but unfortunately i dont get any results. I tried evrythig i know, but i dont know what is going on and why styles aren't changing at all



      Here is parent :



          constructor(props) {
      super(props);
      this.state = {
      number: 1,
      cords: [

      ],
      choosenCords: [

      ],
      style: {flex:1,flexDirection:'row',backgroundColor:'red'}
      };
      }
      <View style={{ marginTop: 3 }}>
      <ListItem style={this.state.style} test={this.state.test} title={item.timestamp} context={item.longtitude + " " + item.latitude} click={this.getData.bind(this, item.longtitude, item.latitude, item.timestamp)} />
      </View>

      getData = async(x, y, z) => {

      let tempTab =
      tempTab.push(x)
      tempTab.push(y)
      tempTab.push(z)
      const changeTest = this.state.test * (-1)
      await this.setState({
      choosenCords: [...this.state.choosenCords, tempTab],
      style: {flex:1,flexDirection:'row',backgroundColor:'blue'}
      })
      }


      }
      This fragment of code represent changing style onPress. "choosenCords" are changing, but "style" don't.



      Here is child:



      class ListItem extends Component {
      constructor(props) {
      super(props);
      this.state = {
      test:this.props.test
      };
      }

      render() {
      return (
      <View style={this.props.style}>
      <Image
      source={require('../Images/gps.png')}
      style={{ borderWidth: 3, borderColor: '#7887AB', borderRadius: 50, marginLeft: 15, marginTop: 10 }}
      />
      <View style={{ flex: 1, flexDirection: "column", marginBottom: 15, marginLeft: 10 }}>
      <Text style={{ marginLeft: 10, fontSize: 16 }}>
      {
      "Timestamp: " + this.props.title
      }
      </Text>
      <Text style={{ marginLeft: 15, fontSize: 15 }}>
      {
      "Cords:" + this.props.context
      }
      </Text>
      </View>
      <TouchableHighlight
      underlayColor={'transparent'}
      onPress={
      this.props.click
      }>
      <Image
      source={
      require('../Images/check.png')
      }
      style={{ marginRight: 20 }}
      />
      </TouchableHighlight>
      </View>
      );

      }


      Could someone help me with that?










      share|improve this question














      I've got a problem with my app. I'm trying to change style in my child component using states but unfortunately i dont get any results. I tried evrythig i know, but i dont know what is going on and why styles aren't changing at all



      Here is parent :



          constructor(props) {
      super(props);
      this.state = {
      number: 1,
      cords: [

      ],
      choosenCords: [

      ],
      style: {flex:1,flexDirection:'row',backgroundColor:'red'}
      };
      }
      <View style={{ marginTop: 3 }}>
      <ListItem style={this.state.style} test={this.state.test} title={item.timestamp} context={item.longtitude + " " + item.latitude} click={this.getData.bind(this, item.longtitude, item.latitude, item.timestamp)} />
      </View>

      getData = async(x, y, z) => {

      let tempTab =
      tempTab.push(x)
      tempTab.push(y)
      tempTab.push(z)
      const changeTest = this.state.test * (-1)
      await this.setState({
      choosenCords: [...this.state.choosenCords, tempTab],
      style: {flex:1,flexDirection:'row',backgroundColor:'blue'}
      })
      }


      }
      This fragment of code represent changing style onPress. "choosenCords" are changing, but "style" don't.



      Here is child:



      class ListItem extends Component {
      constructor(props) {
      super(props);
      this.state = {
      test:this.props.test
      };
      }

      render() {
      return (
      <View style={this.props.style}>
      <Image
      source={require('../Images/gps.png')}
      style={{ borderWidth: 3, borderColor: '#7887AB', borderRadius: 50, marginLeft: 15, marginTop: 10 }}
      />
      <View style={{ flex: 1, flexDirection: "column", marginBottom: 15, marginLeft: 10 }}>
      <Text style={{ marginLeft: 10, fontSize: 16 }}>
      {
      "Timestamp: " + this.props.title
      }
      </Text>
      <Text style={{ marginLeft: 15, fontSize: 15 }}>
      {
      "Cords:" + this.props.context
      }
      </Text>
      </View>
      <TouchableHighlight
      underlayColor={'transparent'}
      onPress={
      this.props.click
      }>
      <Image
      source={
      require('../Images/check.png')
      }
      style={{ marginRight: 20 }}
      />
      </TouchableHighlight>
      </View>
      );

      }


      Could someone help me with that?







      react-native






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 28 '18 at 11:23









      Piotr MazurekPiotr Mazurek

      1




      1
























          3 Answers
          3






          active

          oldest

          votes


















          0














          You have to do like this:



          const customStyle= this.state.test ? styles.custom_1: styles.custom_2

          return <View
          style={[ styles.anyStyle, customStyle]}
          />;


          Define your custom style variable, set it based on state, then use it as an array for your element.






          share|improve this answer
























          • It still doesn't change color. In console.log i see that parent state is changing but color stay the same

            – Piotr Mazurek
            Nov 28 '18 at 11:49













          • It's changing color before i add child do parent component. I need to change it color when it is already in there

            – Piotr Mazurek
            Nov 28 '18 at 11:58











          • Missing the spread operator. return <View style={[ ...styles.anyStyle, ...customStyle]} />;

            – Laurie Williams
            Nov 28 '18 at 12:07











          • it is working now? was helpful my answer ?

            – oma
            Nov 28 '18 at 12:56



















          0














          The child component does not automatically update when the state of the parent component changes. You'll need to update the state of the child component manually when the parent sends new props.



          //in child component
          componentDidUpdate(previousProps, previousState){
          if(previousProps.style !== this.props.style){
          //update child state here
          this.setState({style: this.props.style})
          }
          }


          Now instead of using "style={this.props.style}" in the child, use "style={this.state.style}"






          share|improve this answer
























          • Using PureComponent for the child component is often a better way to handle props changes !

            – Hugo Laplace
            Nov 28 '18 at 23:57



















          0














          It is happening because when you update your state, child component will not update automatically. you will get new updated value in componentWillReceiveProps() method.



          your ListItem class will be like below:



            class ListItem extends Component {
          constructor(props) {
          super(props);
          this.state = {
          test:this.props.test,
          style:'' // take style into your state
          };
          }
          componentWillMount(){
          this.setState({style: this.props.style}) //set style
          }
          componentWillReceiveProps(newProps){
          //called when you update style
          if(newProps.style !== this.props.style){
          this.setState({style: newProps.style})
          }
          }
          render() {
          return (
          <View style={this.state.style}> //set style for views from state
          // add your views here
          </View>
          );
          }
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53518324%2freact-native-couldnt-change-style-using-state%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You have to do like this:



            const customStyle= this.state.test ? styles.custom_1: styles.custom_2

            return <View
            style={[ styles.anyStyle, customStyle]}
            />;


            Define your custom style variable, set it based on state, then use it as an array for your element.






            share|improve this answer
























            • It still doesn't change color. In console.log i see that parent state is changing but color stay the same

              – Piotr Mazurek
              Nov 28 '18 at 11:49













            • It's changing color before i add child do parent component. I need to change it color when it is already in there

              – Piotr Mazurek
              Nov 28 '18 at 11:58











            • Missing the spread operator. return <View style={[ ...styles.anyStyle, ...customStyle]} />;

              – Laurie Williams
              Nov 28 '18 at 12:07











            • it is working now? was helpful my answer ?

              – oma
              Nov 28 '18 at 12:56
















            0














            You have to do like this:



            const customStyle= this.state.test ? styles.custom_1: styles.custom_2

            return <View
            style={[ styles.anyStyle, customStyle]}
            />;


            Define your custom style variable, set it based on state, then use it as an array for your element.






            share|improve this answer
























            • It still doesn't change color. In console.log i see that parent state is changing but color stay the same

              – Piotr Mazurek
              Nov 28 '18 at 11:49













            • It's changing color before i add child do parent component. I need to change it color when it is already in there

              – Piotr Mazurek
              Nov 28 '18 at 11:58











            • Missing the spread operator. return <View style={[ ...styles.anyStyle, ...customStyle]} />;

              – Laurie Williams
              Nov 28 '18 at 12:07











            • it is working now? was helpful my answer ?

              – oma
              Nov 28 '18 at 12:56














            0












            0








            0







            You have to do like this:



            const customStyle= this.state.test ? styles.custom_1: styles.custom_2

            return <View
            style={[ styles.anyStyle, customStyle]}
            />;


            Define your custom style variable, set it based on state, then use it as an array for your element.






            share|improve this answer













            You have to do like this:



            const customStyle= this.state.test ? styles.custom_1: styles.custom_2

            return <View
            style={[ styles.anyStyle, customStyle]}
            />;


            Define your custom style variable, set it based on state, then use it as an array for your element.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 28 '18 at 11:28









            omaoma

            99559




            99559













            • It still doesn't change color. In console.log i see that parent state is changing but color stay the same

              – Piotr Mazurek
              Nov 28 '18 at 11:49













            • It's changing color before i add child do parent component. I need to change it color when it is already in there

              – Piotr Mazurek
              Nov 28 '18 at 11:58











            • Missing the spread operator. return <View style={[ ...styles.anyStyle, ...customStyle]} />;

              – Laurie Williams
              Nov 28 '18 at 12:07











            • it is working now? was helpful my answer ?

              – oma
              Nov 28 '18 at 12:56



















            • It still doesn't change color. In console.log i see that parent state is changing but color stay the same

              – Piotr Mazurek
              Nov 28 '18 at 11:49













            • It's changing color before i add child do parent component. I need to change it color when it is already in there

              – Piotr Mazurek
              Nov 28 '18 at 11:58











            • Missing the spread operator. return <View style={[ ...styles.anyStyle, ...customStyle]} />;

              – Laurie Williams
              Nov 28 '18 at 12:07











            • it is working now? was helpful my answer ?

              – oma
              Nov 28 '18 at 12:56

















            It still doesn't change color. In console.log i see that parent state is changing but color stay the same

            – Piotr Mazurek
            Nov 28 '18 at 11:49







            It still doesn't change color. In console.log i see that parent state is changing but color stay the same

            – Piotr Mazurek
            Nov 28 '18 at 11:49















            It's changing color before i add child do parent component. I need to change it color when it is already in there

            – Piotr Mazurek
            Nov 28 '18 at 11:58





            It's changing color before i add child do parent component. I need to change it color when it is already in there

            – Piotr Mazurek
            Nov 28 '18 at 11:58













            Missing the spread operator. return <View style={[ ...styles.anyStyle, ...customStyle]} />;

            – Laurie Williams
            Nov 28 '18 at 12:07





            Missing the spread operator. return <View style={[ ...styles.anyStyle, ...customStyle]} />;

            – Laurie Williams
            Nov 28 '18 at 12:07













            it is working now? was helpful my answer ?

            – oma
            Nov 28 '18 at 12:56





            it is working now? was helpful my answer ?

            – oma
            Nov 28 '18 at 12:56













            0














            The child component does not automatically update when the state of the parent component changes. You'll need to update the state of the child component manually when the parent sends new props.



            //in child component
            componentDidUpdate(previousProps, previousState){
            if(previousProps.style !== this.props.style){
            //update child state here
            this.setState({style: this.props.style})
            }
            }


            Now instead of using "style={this.props.style}" in the child, use "style={this.state.style}"






            share|improve this answer
























            • Using PureComponent for the child component is often a better way to handle props changes !

              – Hugo Laplace
              Nov 28 '18 at 23:57
















            0














            The child component does not automatically update when the state of the parent component changes. You'll need to update the state of the child component manually when the parent sends new props.



            //in child component
            componentDidUpdate(previousProps, previousState){
            if(previousProps.style !== this.props.style){
            //update child state here
            this.setState({style: this.props.style})
            }
            }


            Now instead of using "style={this.props.style}" in the child, use "style={this.state.style}"






            share|improve this answer
























            • Using PureComponent for the child component is often a better way to handle props changes !

              – Hugo Laplace
              Nov 28 '18 at 23:57














            0












            0








            0







            The child component does not automatically update when the state of the parent component changes. You'll need to update the state of the child component manually when the parent sends new props.



            //in child component
            componentDidUpdate(previousProps, previousState){
            if(previousProps.style !== this.props.style){
            //update child state here
            this.setState({style: this.props.style})
            }
            }


            Now instead of using "style={this.props.style}" in the child, use "style={this.state.style}"






            share|improve this answer













            The child component does not automatically update when the state of the parent component changes. You'll need to update the state of the child component manually when the parent sends new props.



            //in child component
            componentDidUpdate(previousProps, previousState){
            if(previousProps.style !== this.props.style){
            //update child state here
            this.setState({style: this.props.style})
            }
            }


            Now instead of using "style={this.props.style}" in the child, use "style={this.state.style}"







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 28 '18 at 18:39









            Kamran FekriKamran Fekri

            412




            412













            • Using PureComponent for the child component is often a better way to handle props changes !

              – Hugo Laplace
              Nov 28 '18 at 23:57



















            • Using PureComponent for the child component is often a better way to handle props changes !

              – Hugo Laplace
              Nov 28 '18 at 23:57

















            Using PureComponent for the child component is often a better way to handle props changes !

            – Hugo Laplace
            Nov 28 '18 at 23:57





            Using PureComponent for the child component is often a better way to handle props changes !

            – Hugo Laplace
            Nov 28 '18 at 23:57











            0














            It is happening because when you update your state, child component will not update automatically. you will get new updated value in componentWillReceiveProps() method.



            your ListItem class will be like below:



              class ListItem extends Component {
            constructor(props) {
            super(props);
            this.state = {
            test:this.props.test,
            style:'' // take style into your state
            };
            }
            componentWillMount(){
            this.setState({style: this.props.style}) //set style
            }
            componentWillReceiveProps(newProps){
            //called when you update style
            if(newProps.style !== this.props.style){
            this.setState({style: newProps.style})
            }
            }
            render() {
            return (
            <View style={this.state.style}> //set style for views from state
            // add your views here
            </View>
            );
            }
            }





            share|improve this answer




























              0














              It is happening because when you update your state, child component will not update automatically. you will get new updated value in componentWillReceiveProps() method.



              your ListItem class will be like below:



                class ListItem extends Component {
              constructor(props) {
              super(props);
              this.state = {
              test:this.props.test,
              style:'' // take style into your state
              };
              }
              componentWillMount(){
              this.setState({style: this.props.style}) //set style
              }
              componentWillReceiveProps(newProps){
              //called when you update style
              if(newProps.style !== this.props.style){
              this.setState({style: newProps.style})
              }
              }
              render() {
              return (
              <View style={this.state.style}> //set style for views from state
              // add your views here
              </View>
              );
              }
              }





              share|improve this answer


























                0












                0








                0







                It is happening because when you update your state, child component will not update automatically. you will get new updated value in componentWillReceiveProps() method.



                your ListItem class will be like below:



                  class ListItem extends Component {
                constructor(props) {
                super(props);
                this.state = {
                test:this.props.test,
                style:'' // take style into your state
                };
                }
                componentWillMount(){
                this.setState({style: this.props.style}) //set style
                }
                componentWillReceiveProps(newProps){
                //called when you update style
                if(newProps.style !== this.props.style){
                this.setState({style: newProps.style})
                }
                }
                render() {
                return (
                <View style={this.state.style}> //set style for views from state
                // add your views here
                </View>
                );
                }
                }





                share|improve this answer













                It is happening because when you update your state, child component will not update automatically. you will get new updated value in componentWillReceiveProps() method.



                your ListItem class will be like below:



                  class ListItem extends Component {
                constructor(props) {
                super(props);
                this.state = {
                test:this.props.test,
                style:'' // take style into your state
                };
                }
                componentWillMount(){
                this.setState({style: this.props.style}) //set style
                }
                componentWillReceiveProps(newProps){
                //called when you update style
                if(newProps.style !== this.props.style){
                this.setState({style: newProps.style})
                }
                }
                render() {
                return (
                <View style={this.state.style}> //set style for views from state
                // add your views here
                </View>
                );
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 29 '18 at 9:07









                Patel DharaPatel Dhara

                37818




                37818






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53518324%2freact-native-couldnt-change-style-using-state%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                    Calculate evaluation metrics using cross_val_predict sklearn

                    Insert data from modal to MySQL (multiple modal on website)