LoginSignup
3
1

More than 1 year has passed since last update.

【React】The above error occurred in the <img> componentの対処法【styled-components】

Last updated at Posted at 2021-07-29

症状

Reactでstyled-componentsを使用して、画面レイアウトの修正をしていたところ、下記のエラーが発生し画面が白飛びしてしましました。
翻訳すると、「上記のエラーはコンポーネントで発生しました」となりました。
imgコンポーネントで不具合が起きているようです。

error
index.js:1 The above error occurred in the <img> component:

    at img
    at O (http://localhost:3001/static/js/vendors~main.chunk.js:71248:6)
    at div
    at O (http://localhost:3001/static/js/vendors~main.chunk.js:71248:6)
    at div
    at O (http://localhost:3001/static/js/vendors~main.chunk.js:71248:6)
    at div
    at O (http://localhost:3001/static/js/vendors~main.chunk.js:71248:6)
    at Home (http://localhost:3001/static/js/main.chunk.js:8060:86)
Home.jsx
import React from "react";
import styled from "styled-components";
import userImage from "./images/user-image.jpg";

const userImageWrapper = styled.img`
`;

const userImage = styled.div`
`;

export const Home = ()=> {

  return (
    <userImageWrapper>
      <userImage src={userImage} alt={userImage}></userImage>
    </userImageWrapper>
  )
}

解決方法

userImageコンポーネントにimg、その親のコンポーネントにdivのスタイルに変更することで解決しました。
imgを表示させるコンポーネントではなく、その親のWrapperコンポーネントに対して、imgタグが適用されていたため、エラーが起こっていたようです。

Home.jsx
import React from "react";
import styled from "styled-components";
import userImage from "./images/user-image.jpg";

const userImageWrapper = styled.div`
`;

const userImage = styled.img`
`;

export const Home = ()=> {

  return (
    <userImageWrapper>
      <userImage src={userImage} alt={userImage}></userImage>
    </userImageWrapper>
  )
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1