I'm using Relay Modern (compat). I have a fragment that contains a field that has one argument, but I can't find a way of passing the variable value from the parent component:
// MyFragmentComponent.jsx
class MyFragmentComponent extends Component {...}
const fragments = {
employee: graphql`
fragment MyFragmentComponent_employee on Employee {
hoursWorked(includeOvertime: $includeOvertime)
dob
fullName
id
}
`,
}
export default Relay.createFragmentContainer(MyFragmentComponent, fragments)
It will end up saying $includeOvertime
is not defined. The context where this component is being rendered looks like this:
// MyRootComponent.jsx
class MyRootComponent extends Component {
render() {
const { employee } = this.props
const includeOvertime = //... value is available here
return (
<div>
<MyFragmentComponent employee={employee} />
</div>
)
}
}
const query = graphql`
query MyRootComponentQuery($employeeId: String!) {
employee(id: $employeeId) {
fullName
...MyFragmentComponent_employee
}
}
`
export default MyUtils.createQueryRenderer(MyRootComponent, query) // this just returns a QueryRenderer
With relay classic you would pass variables this way:
....
employee(id: $employeeId) {
fullName
${MyFragmentComponent.getFragment('employee', variables)}
}
How can I achieve the same with relay modern?
Using
@argumentDefinitions
and@arguments
directives seems to be the way to go. In relay versions before 1.4.0graphql.experimental
had to be used instead ofgraphql
.In the fragment definition:
If you want the argument to be required:
In the parent component you should specify the arguments for the fragment like this:
In this page in the official relay docs there is an example of directives for defining/passing arguments.
UPDATE:
UPDATE: