How add dynamic id to FormattedMessage in react intl

I have state area with description field and from server i give state eg. STARTED, FINISH, ARCHIVED.

And i use FormattedMessage for different language like this:

<FormattedMessage id={"state." + this.props.state} defaultMessage="defaultState" />

It isn't working.

is any solution for this case?

UPDATE: Default state isn't. I load data from server.

My component:

class State extends Component {

render() {
    return (
        <Card>
            <CardBody className="text-center">
                <Button className="bg-primary">
                    <FormattedMessage id={"state." + this.props.query.findCourseUserStatus.state} defaultMessage="defaultState" />
                    }
                </Button>
            </CardBody>
        </Card>
    );
}
}

export default createFragmentContainer(
    State,
    graphql`
    fragment State_query on Query {
          findCourseUserStatus(id: $courseId){
          courseId
          state
          }
    },
    `
);

Upvotes: 1

Views: 3920

Answers (1)

Prashant Sharma
Prashant Sharma

Reputation: 114

enter code here

Its an old question but i would like to answer it for future reference,

There are two ways:

  1. for class component we can use injectIntl as hoc.

        import {injectIntl } from 'react-intl';
    
        class State extends Component {
           render() {
              return (
            <Card>
                <CardBody className="text-center">
                    <Button className="bg-primary">
                        {this.props.intl.formatMessage({id:{"state." + this.props.query.findCourseUserStatus.state},
            defaultMessage="defaultState" })}
                    </Button>
                </CardBody>
            </Card>
        );
        }
    
    }
    
    export default injectIntl(State);
    
  2. The upgraded version of react-intl provides with injectIntl hooks for functional component

The usage would be like this.

import {useIntl } from 'react-intl';

const State  = (props) {
     const intl = useIntl();
            <Card>
                <CardBody className="text-center">
                    <Button className="bg-primary">
                        {intl.formatMessage({id:{"state." + props.query.findCourseUserStatus.state},
            defaultMessage="defaultState" })}
                    </Button>
                </CardBody>
            </Card>
        );
        }


    export default State;

Upvotes: 1

Related Questions