简体   繁体   中英

How to automatically change text depending on boolean value in JSON file

I have a JSON file:

[
 {
 "id": 1,
 "text": "Hello",
 "availability": false
 },
 {
 "id": 2,
 "text": "Hello",
 "availability": true
 }
]

What I would like to achieve is for the text to automatically change from hello to goodbye when availability : false . If availability : true then I would like it to stay the same displaying 'Hello'.

This is my code so far:

import React, { Component } from 'react';
import './styles.css'

class GetOnlinePosts extends Component {
constructor(props){
super(props);
this.state = {
    error : null,
    isLoaded : false,
    posts : []          
 };
}
 componentDidMount(){
 fetch("https://api.myjson.com")
 .then( response => response.json())
 .then(
    (result) => {
        this.setState({
            isLoaded : true,
            posts : result
        });
    },
    (error) => {
        this.setState({
            isLoaded: true,
            error
        })
      },
    )
  }
 render() {
 const {error, isLoaded, posts} = this.state;
 const orderedPosts = [...posts.filter((post) => post.availability), ...posts.filter((post) => !post.availability)]
 if(error){
    return <div>Error in loading</div>
 }else if (!isLoaded) {
    return <div>Loading ...</div>
 }else{
    return(
        <div>
            <div className="tiles">
            {
                orderedPosts.map(post => (
                    <div key={post.id}>
                     <div className="tile">
                         <p className="greeting">{post.text}</p>
                     </div> 
                </div>
                ))
            }
            </div>
        </div>
    );
   }
  }
 }

 export default GetOnlinePosts;

Any help on changing the text from 'Hello' to 'Goodbye' when availability : false and keeping the text 'Hello' when availability : true would be great. thanks in advance

Please add condition to map

<p className="greeting">{post.availability ? post.text : 'Goodbye'}</p>

Please changes this line

import React, { Component } from 'react';
import './styles.css'

class GetOnlinePosts extends Component {
constructor(props){
super(props);
this.state = {
    error : null,
    isLoaded : false,
    posts : []          
 };
}
 componentDidMount(){
 fetch("https://api.myjson.com")
 .then( response => response.json())
 .then(
    (result) => {
        this.setState({
            isLoaded : true,
            posts : result
        });
    },
    (error) => {
        this.setState({
            isLoaded: true,
            error
        })
      },
    )
  }
 render() {
 const {error, isLoaded, posts} = this.state;
 const orderedPosts = [...posts.filter((post) => post.availability), ...posts.filter((post) => !post.availability)]
 if(error){
    return <div>Error in loading</div>
 }else if (!isLoaded) {
    return <div>Loading ...</div>
 }else{
    return(
        <div>
            <div className="tiles">
            {
                orderedPosts.map(post => (
                    <div key={post.id}>
                     <div className="tile">
                         <p className="greeting">{post.availability ? post.text : 'Goodbye'}</p> // Change this line
                     </div> 
                </div>
                ))
            }
            </div>
        </div>
    );
   }
  }
 }

 export default GetOnlinePosts;

Somewhere after fetching, map the results like this:

const processPost = post => post.availability
    ? post 
    : Object.assign({}, post, { text: "Goodbye" });

// ...

fetch("https://api.myjson.com")
    .then(response => response.json())
    .then(posts => posts.map(processPost))

This is easy to achieve with simple ternary statement.

return(
    <div>
        <div className="tiles">
        {
            orderedPosts.map(post => (
                <div key={post.id}>
                 <div className="tile">
                     <p className="greeting">{post.availability ? post.text : 'Goodbye!'}</p>
                 </div> 
            </div>
            ))
        }
        </div>
    </div>
);

Docs for ternary: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

You can use ternary operator for displaying text.I hope it will helps you.

 import React, { Component } from 'react';
import './styles.css'

class GetOnlinePosts extends Component {
constructor(props){
super(props);
this.state = {
    error : null,
    isLoaded : false,
    posts : []          
 };
}
 componentDidMount(){
 fetch("https://api.myjson.com")
 .then( response => response.json())
 .then(
    (result) => {
        this.setState({
            isLoaded : true,
            posts : result
        });
    },
    (error) => {
        this.setState({
            isLoaded: true,
            error
        })
      },
    )
  }
 render() {
 const {error, isLoaded, posts} = this.state;
 const orderedPosts = [...posts.filter((post) => post.availability), ...posts.filter((post) => !post.availability)]
 if(error){
    return <div>Error in loading</div>
 }else if (!isLoaded) {
    return <div>Loading ...</div>
 }else{
    return(
        <div>
            <div className="tiles">
            {
                orderedPosts.map(post => (
                    <div key={post.id}>
                     <div className="tile">
                     {
                post.availability:( <p className="greeting">{post.text}</p>)? 
               (<p className="greeting">Goodbye</p>)
                 }

                     </div> 
                </div>
                ))
            }
            </div>
        </div>
    );
   }
  }
 }

 export default GetOnlinePosts;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM