1

Hello I have a website built in Craft 3. I have some components built in React but typically the site is served using Twig templates.

How can I make an axios call to craft to request the page's entry blocks, sections, etc? Is this possible?

1

Yes you can. I use Craft 3 as an headless CMS for React or for any other javascript framework.

You have various options to do this, the most know ones are described here: https://docs.craftcms.com/v3/dev/headless.html#app

I would recommend you to use the CraftQL plugin. My example below is using ReactJS, Axios and CraftQL within CraftCMS. This plugin (CraftQL) allows you to access your Sections, Entries, Categories, etc... by doing queries to a GraphQL api endpoint in Craft CMS.

See more about the plugin here: https://github.com/markhuot/craftql

This is an example for ReactJS and with Axios on componentDidMount:

  componentDidMount() {
    // data query
    // your GraphQL query should go here!!
    const queryData = {
      query: `{
        helloWorld
      }`
    };

    // GraphQL API headers
    // The values for craftql_token_type and craftql_token_value are in
    // the settings of the plugin in Craft CP (Control Panel). 
    // You can update the access to the GraphQL api endpoint there
    const queryHeaders = {
      headers: {
        'Authorization': `craftql_token_type craftql_token_value`
      }
    };

    // Axios POST request to GraphQL API url
    axios
      .post(api_url, queryData, queryHeaders)
      .then((response) => {
        if (response.data.data.errors) {
          // do something
        } else {
          // do something
          this.setState({
            data: response.data
          });
        }
      })
      .catch(error => {
        this.setState({
          error: true
        });
      });
  }

Hope this helps!

:)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.