Vue: Child component not rendering string prop

Hey there, I'm currently exploring the ins and outs of Vue and diving into its one-way data bind model, component registration, and passing props.

Within my index.js file, I've set up my parent component to render a single child component for now:

import Vue from 'vue'
import StyledTitle from './components/StyledTitle'

new Vue({
  el: '#app',
  components: {
    StyledTitle,
  },
})

The child component in question is called StyledTitle.js:

import Vue from 'vue'
import styled from 'vue-styled-components'

const StyledTitle = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #ff4947;
  &:hover,
  &:focus {
    color: #f07079;
  }
`

Vue.component('styled-title', {
  props: ['text'],
  components: {
    'styled-title': StyledTitle,
  },
  template: `<StyledTitle>{{ text }}</StyledTitle>`,
})

export default StyledTitle

Now, when I look at my HTML code, I expect it to render a red "Hi":

<div id="app">
   <styled-title text="Hi"></styled-title>
</div>

Unfortunately, the "Hi" is not showing up as expected, and I'm finding that the props value is coming up as undefined. Transitioning from React, I'm curious as to why this setup isn't working. Any help would be appreciated! Thanks!

P.S. Here's a screenshot of my Vue devtools:

Answer №1

Your problem lies in the StyledTitle.js file, where a regular styled <h1> component is being exported with a default slot for its content instead of your custom component that accepts a text prop.

If you prefer to use a prop-based component, you should export that one instead of the one from vue-styled-components. It's also recommended to avoid global component registration in this scenario.

Here is an example:

// StyledTitle.js
import styled from 'vue-styled-components'

// create a styled title locally
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #ff4947;
  &:hover,
  &:focus {
    color: #f07079;
  }
`

// now export your custom wrapper component
export default {
  name: 'StyledTitle',
  props: ['text'],
  components: {
    Title, // locally register your styled Title as "Title"
  },
  template: `<Title>{{ text }}</Title>`,
})

Since your component doesn't have any state, it can be made purely functional. Using a render function will also be beneficial, especially if the Vue runtime doesn't include the template compiler by default (common in most Vue CLI apps)

export default {
  name: 'StyledTitle',
  functional: true,
  props: { text: String },
  render: (h, { props }) => h(Title, props.text)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The slash character is escaped by the RegExp constructor, but the dot character is

Consider the following code: console.log(new RegExp('.git')); console.log(new RegExp('scripts/npm')); which produces the following output: /.git/ /scripts\/npm/ The puzzling question here is - why does it escape the slash in &a ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

The JSHint error message that appeared was looking for an identifier but found the reserved word 'import' instead

I am encountering a warning message in vscode: There is an 'import' statement that is causing an issue. The error message reads: Expected an identifier and instead saw 'import' (a reserved word). (W024)jshint(W024) Here is the code s ...

What is the best way to share models across different node.js projects?

In my setup, I have two node.js projects - project A and project B. Project A serves as the main project, while project B is more of an "ad-hoc" project with a specific purpose. The challenge lies in the fact that project B requires access to project A&apo ...

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...

What alternative methods can be used to render a React component without relying on the ReactDOM.render

Can a React component be rendered simply by referencing it with its name? For example: <div> <MyComponent/> </div> In all the tutorials and examples I've seen, ReactDOM.render function is used to render the component onto the ta ...

Any ideas on how to extract binary data from PHP passthru using a JavaScript ajax request?

I am facing an issue with retrieving and playing an audio file from a server using JavaScript. The ajax call in my code doesn't seem to callback, and I'm not certain if I'm handling the audio correctly in JavaScript. Below is the PHP file t ...

Ways to simulate a function that is a part of an internal object

Is there a way to mock a method from an object within my UnderTest class? When the Update method is triggered by an event from a child component, I need to mock the service.saveNewElement(data) method in order to test data in the then() block. <script ...

Encountering an error when integrating my library with MUI

Currently, I am working on developing a library that wraps MUI. One of the components I created is a Button, and here is the code snippet for it: import React, { ReactNode } from 'react' import Button from '@mui/material/Button'; impor ...

Encountering a TypeError when attempting to read the property 'name' of undefined while submitting a form in node.js

I'm currently working on a node Js project and I'm encountering an issue while saving form values to a mongoDB database. I've been troubleshooting but can't seem to pinpoint the cause of this error. The error is occurring at the router. ...

Is it possible to develop a function that can verify various input values and modify their appearance as needed?

I am currently working on creating a form and faced with the challenge of simplifying my code using a function. Specifically, I want to write JavaScript code that will check all input fields in the form to ensure they are filled. If any field is left emp ...

Leveraging AngularJS services within an Angular service

I am currently in the process of transitioning my AngularJS application to Angular. To facilitate this transition, I plan to create a hybrid application that combines both frameworks until the conversion is complete. However, I have encountered an issue wi ...

Enhance your Vue.js application by dynamically adding a class when a computed value

Just delving into the world of vue.js and I have a simple query. I've been following a tutorial but now I'd like to add my own touch to it :-P Whenever there is a change in my rank, I would like to include a CSS class for animating the label. Ho ...

Is there a way to dynamically update a game's highscore from a database without having to refresh the page?

I developed a JS snake game using HTML5 canvas. In the event that the user loses, the score is transmitted to the database through an AJAX call in my PHP script. The PHP code then compares this score to the current highscore and updates it if needed. Howev ...

Challenge encountered in posting a variable generated through ajax

Embarking on my first attempt at utilizing ajax has been quite challenging. Essentially, when an option is selected from the initial field, javascript and xml trigger a php script that generates the next dropdown menu based on information fetched from an S ...

Having trouble getting my ReactJS page to load properly

I am currently linked to my server using the command npm install -g http-server in my terminal, and everything seems to be working smoothly. I just want to confirm if my h1 tag is functional so that I can proceed with creating a practice website. I have a ...

Using AJAX and PHP to dynamically fill HTML drop-down menus

In order to populate the DropDown controls on my HTML Form dynamically, I have implemented a code that utilizes AJAX to make a call to a .php file. This .php file is responsible for filling the DropDown control with values from a single column. Throughout ...

problem with the clientHeight attribute in window event handlers

The component below is designed to react to changes in window resize based on the container height. However, there seems to be an issue where the containerHeight variable increases as the window size decreases, but does not decrease when I make the window ...

Is there a way for me to retrieve the variable from one function and use it in another

I have a tool for managing images with descriptions that allows me to edit both the text and the image file. The challenge is saving the modifications I make in my database. Currently, I can only save changes if I modify the image itself. If I only update ...