Insert a link

confused about how to add a link …

I tried:

let attrs={ title: 'mylink', href:'google.com' }
let schema=view.state.schema
let node=schema.text(attrs.title)
node=node.mark(schema.marks.link.create(attrs))
view.dispatch(view.state.tr.replaceSelectionWith(node))

but I just get the text ‘mylink’ and not a link:(

what’s the correct way here ?

mark takes an array of marks, not a single mark. You could also pass the array of marks to schema.text directly, as second argument.

ok thx ! (would be great if text and mark will throw if marks is not an array…)

Still no luck, I tried:

let attrs={ title: 'mylink', href:'google.com' }
let schema=view.state.schema
let node=schema.text(attrs.title, [schema.marks.link.create(attrs)])
view.dispatch(view.state.tr.replaceSelectionWith(node))	

but I still get a ‘mylink’ text without the link mark

(I inspected node and it does have a marks array with a single link mark)

what’s wrong ?

ok I realized I need to set inheritMarks to false

So this works:

let attrs={ title: 'mylink', href:'google.com' }
let schema=view.state.schema
let node=schema.text(attrs.title, [schema.marks.link.create(attrs)])
view.dispatch(view.state.tr.replaceSelectionWith(node, false))
1 Like